gpt4 book ai didi

python - 在没有控制台的情况下使用 Popen 在 python 中运行进程

转载 作者:IT老高 更新时间:2023-10-28 21:09:15 26 4
gpt4 key购买 nike

我有一个带有 GUI 的程序,它通过 Popen 调用运行外部程序:

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

但是无论我做什么,都会弹出一个控制台(我也尝试将它传递给 NUL 作为文件句柄)。有没有办法在不获取我调用的二进制文件来释放其控制台的情况下做到这一点?

最佳答案

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

请注意,有时抑制控制台会导致子进程调用失败并显示“错误 6:无效句柄”。一个快速的解决方法是重定向 stdin,如下所述:Python running as Windows Service: OSError: [WinError 6] The handle is invalid

关于python - 在没有控制台的情况下使用 Popen 在 python 中运行进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1813872/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com