subprocess.Popen在cx_freeze之后的行为 [英] subprocess.Popen behavior after cx_freeze

查看:74
本文介绍了subprocess.Popen在cx_freeze之后的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some python code using subprocess.Popen to open a console application and get stdout/stderr from it.

从解释器中启动可以正常工作,并且按预期进行。

Launching from the interpreter works fine and as intended.

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

After using cx_freeze with --base-name Win32GUI option the Popen pops up in a console window now and I can't capture stdout/stderr. If I remove --base-name Win32GUI it works as intended but I now have a console behind the UI.

这是代码(我在没有 startupinfo 且没有 shell = False 的情况下尝试了它):

Here is the code (I've tried it without startupinfo and without 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()来获取标准输出/ stderr

I'm using out, err = p.communicate() to grab stdout/stderr

推荐答案

好的,我找到了解决方案。由于Windows GUI应用程序的stdout句柄不存在,因此子进程似乎继承了该行为。因此,解决方法是一个简单的方法,更复杂的是涉及win32api并为其创建管道(未尝试此方法)。

Okay I found a solution. It looks like since its a windows GUI Application stdout handle doesn't exist and it looks like subprocess inherits that behavior. So a workaround is a simple one and a more complicated one involved with the win32api and creating a pipe for it (didn't try this method).

最后工作:

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()

这篇关于subprocess.Popen在cx_freeze之后的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆