使用 os.system() 或 subprocess.call() 时如何隐藏控制台? [英] 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?
推荐答案
进程STARTUPINFO
可以隐藏控制台窗口:
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)
以上仍然是一个具有控制台 I/O 有效句柄的控制台进程(通过对 GetStdHandle
返回的句柄调用 GetFileType
进行验证).它只是没有窗口并且不继承父级的控制台(如果有的话).
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)
在这种情况下,子进程的标准句柄(即 GetStdHandle
)为 0,但您可以将它们设置为打开的磁盘文件或管道,例如 subprocess.DEVNULL
(3.3) 或 subprocess.PIPE
.
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
.
这篇关于使用 os.system() 或 subprocess.call() 时如何隐藏控制台?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!