How do I hide the console when I use os.system() or subprocess.call()?
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
.
How to hide output of subprocess
For python >= 3.3, Redirect the output to DEVNULL:
import os
import subprocess
retcode = subprocess.call(['echo', 'foo'],
stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT)
For python <3.3, including 2.7 use:
FNULL = open(os.devnull, 'w')
retcode = subprocess.call(['echo', 'foo'],
stdout=FNULL,
stderr=subprocess.STDOUT)
It is effectively the same as running this shell command:
retcode = os.system("echo 'foo' &> /dev/null")
Running a process in pythonw with Popen without a console
From here:
import subprocess
def launchWithoutConsole(command, args):
"""Launches 'command' windowless and waits until finished"""
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
return subprocess.Popen([command] + args, startupinfo=startupinfo).wait()
if __name__ == "__main__":
# test with "pythonw.exe"
launchWithoutConsole("d:\\bin\\gzip.exe", ["-d", "myfile.gz"])
Note that sometimes suppressing the console makes subprocess calls fail with "Error 6: invalid handle". A quick fix is to redirect stdin
, as explained here: Python running as Windows Service: OSError: [WinError 6] The handle is invalid
Related Topics
Python3 Flask Asyncio Subprocess in Route Hangs
Find Out Who Is Logged in on Linux Using Python
Python For-In Loop Preceded by a Variable
How to Create a Zip Archive of a Directory
Improve Subplot Size/Spacing with Many Subplots in Matplotlib
Constantly Print Subprocess Output While Process Is Running
What's the Correct Way to Convert Bytes to a Hex String in Python 3
Creating a Dictionary from a CSV File
Else Clause on Python While Statement
Urllib2.Httperror: Http Error 403: Forbidden
How to Use Phantomjs in Python
Why Should I Make a Copy of a Data Frame in Pandas
Behavior of Exec Function in Python 2 and Python 3
How to Merge a List of Dicts into a Single Dict