在pythonw中使用Popen无控制台运行进程

30 投票
6 回答
20453 浏览
提问于 2025-04-15 16:29

我有一个带图形界面的程序,它通过一个叫做 Popen 的方法来运行一个外部程序:

p = subprocess.Popen("<commands>" , stdout=subprocess.PIPE , stderr=subprocess.PIPE , cwd=os.getcwd())
p.communicate()

但是,无论我怎么做,都会弹出一个控制台窗口(我也试过给它传递 NUL 作为文件句柄)。有没有办法在不让我调用的那个程序释放它的控制台的情况下做到这一点呢?

6 个回答

4

根据Python 2.7 的文档Python 3.7 的文档,你可以通过设置creationflags来影响Popen创建进程的方式。特别是,CREATE_NO_WINDOW这个标志会对你很有帮助。

variable = subprocess.Popen(
   "CMD COMMAND", 
   stdout = subprocess.PIPE, creationflags = subprocess.CREATE_NO_WINDOW
)
9

只需使用 subprocess.Popen([command], shell=True) 这个命令就可以了。

37

来自 这里:

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"])

注意,有时候如果关闭控制台,可能会导致子进程调用失败,并出现“错误 6:无效的句柄”。一个简单的解决办法是重定向 stdin,具体可以参考这里的解释:在Windows服务中运行Python时:OSError:[WinError 6] 句柄无效

撰写回答