Akado2009
Akado2009

Reputation: 441

Hiding the console while executing a script on Windows

How can I make my console hide while executing a script? I want to make a separate function to do it (maybe by applying some methods from os/sys, I don't know), so I do not need some solutions like changing script extension from .py to .pyw.

Upvotes: 5

Views: 12796

Answers (3)

martineau
martineau

Reputation: 123393

The way I've done it on Windows 7 is by making a shortcut (or link) that runs my script with the pythonw.exe interpreter, which has no console, instead of the default python.exe.

Just follow these 3 steps:

  1. First create a normal shortcut to your script. One way to do this is to drag the icon for the script file shown in an Explorer window to where you want the shortcut to be (like the desktop) and hold down the Alt key when releasing the mouse button.
  2. Right-click on the just created shortcut and select Properties from the the menu that pops-up.
  3. A Properties dialog for the shortcut will appear. In it insert C:\python27\pythonw.exe and a space before the path to the your script file. if the path to your script has any spaces in it, it must now be enclosed in double quotes._ If you're using another version of Python, you'll also need to change the Python27 accordingly.

i.e. A target of D:\path with spaces in it to\myscript.py would need to be changed

to C:\Python27\pythonw.exe "D:\path with spaces in it to\myscript.py"

You can also change the shortcut's icon here if you wish.

Here's an example:

screenshot of filled in shortcut properties dialog

Update - simpler way: You can also change the extension of your script to .pyw which will cause it to be run with the pythonw.exe instead of the python.exe.

Upvotes: 4

Xantium
Xantium

Reputation: 11605

If you want to hide the window during execution (and your script is for Windows only) then ctypes may be a possibility for you.

Using this answer you could take input and then hide it:

import ctypes

a = input('Input value here:')


kernel32 = ctypes.WinDLL('kernel32')

user32 = ctypes.WinDLL('user32')

SW_HIDE = 0

hWnd = kernel32.GetConsoleWindow()
user32.ShowWindow(hWnd, SW_HIDE)

# Do stuff here

This is running off C ShowWindow(). You can get more (indepth) info from the Windows's own documentation.

Upvotes: 6

helloparth
helloparth

Reputation: 61

You can run a python program in the background by adding a & at the end:

python myfile.py &

If you want to be able to close out your console and have the process run in the background, you might want to check out nohup:

http://linux.die.net/man/1/nohup

Upvotes: 0

Related Questions