Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I hide the console when I use os.system() or subprocess.call()?

I wrote some statements like below:

os.system(cmd) #do something subprocess.call('taskkill /F /IM exename.exe') 

both will pop up a console.

How can I stop it from popping up the console?

like image 719
Synapse Avatar asked Aug 10 '11 05:08

Synapse


People also ask

How do I hide the console window in Python?

Simply save it with a . pyw extension. This will prevent the console window from opening.

What is the difference between subprocess Popen and OS system?

os. system is equivalent to Unix system command, while subprocess was a helper module created to provide many of the facilities provided by the Popen commands with an easier and controllable interface. Those were designed similar to the Unix Popen command.

What is OS Popen in Python?

Description. Python method popen() opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The bufsize argument has the same meaning as in open() function.


1 Answers

The process STARTUPINFO can hide the console window:

si = subprocess.STARTUPINFO() si.dwFlags |= subprocess.STARTF_USESHOWWINDOW #si.wShowWindow = subprocess.SW_HIDE # default subprocess.call('taskkill /F /IM exename.exe', startupinfo=si) 

Or set the creation flags to disable creating the window:

CREATE_NO_WINDOW = 0x08000000 subprocess.call('taskkill /F /IM exename.exe', creationflags=CREATE_NO_WINDOW) 

The above is still a console process with valid handles for console I/O (verified by calling GetFileType on the handles returned by GetStdHandle). It just has no window and doesn't inherit the parent's console, if any.

You can go a step farther by forcing the child to have no console at all:

DETACHED_PROCESS = 0x00000008 subprocess.call('taskkill /F /IM exename.exe', creationflags=DETACHED_PROCESS) 

In this case the child's standard handles (i.e. GetStdHandle) are 0, but you can set them to an open disk file or pipe such as subprocess.DEVNULL (3.3) or subprocess.PIPE.

like image 189
Eryk Sun Avatar answered Sep 23 '22 16:09

Eryk Sun