Skip to main content
 首页 » 编程设计

python之cx_freeze 后的 subprocess.Popen 行为

2024年11月01日8mfryf

我有一些 python 代码使用 subprocess.Popen 打开控制台应用程序并从中获取 stdout/stderr。

从解释器启动工作正常且符合预期。

在将 cx_freeze 与 --base-name Win32GUI 选项一起使用后,Popen 现在会在控制台窗口中弹出,我无法捕获 stdout/stderr。如果我删除 --base-name Win32GUI 它会按预期工作,但我现在在 UI 后面有一个控制台。

这是代码(我试过没有 startupinfo 和 shell=False):

startupinfo = subprocess.STARTUPINFO() 
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW 
            startupinfo.wShowWindow = subprocess.SW_HIDE 
subprocess.Popen(['exe', 'arg1', 'arg2'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, startupinfo=startupinfo) 

我正在使用 out, err = p.communicate() 获取 stdout/stderr

请您参考如下方法:

好的,我找到了解决方案。看起来因为它的 Windows GUI 应用程序 stdout 句柄不存在,而且看起来子进程继承了该行为。因此,一种解决方法是一个简单的解决方法,一个更复杂的解决方法涉及 win32api 并为其创建一个管道(没有尝试过这种方法)。

这是最终起作用的:

startupinfo = subprocess.STARTUPINFO() 
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW 
            startupinfo.wShowWindow = subprocess.SW_HIDE 
stdout_file = tempfile.NamedTemporaryFile(mode='r+', delete=False) 
process = subprocess.Popen(['exe', 'arg1', 'arg2'], stdin=subprocess.PIPE, stdout=stdout_file, stderr=subprocess.PIPE, shell=False, startupinfo=startupinfo) 
return_code = process.wait() 
stdout_file.flush() 
stdout_file.seek(0) # This is required to reset position to the start of the file 
out = stdout_file.read() 
stdout_file.close()