当 exe 失败时,python popen sdtout 没有获得所有输出 [英] python popen sdtout doesn't get all the output when exe fails

查看:24
本文介绍了当 exe 失败时,python popen sdtout 没有获得所有输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 python 新手,并试图在 windows 中从 python 运行 exe 软件.我写了以下代码:

I'm new to python, and trying to run a exe software from python in windows. I wrote the following code:

from subprocess import STDOUT, Popen, PIPE

cmd=r'C:\Users\lenaq\Desktop\sep\WATv16\TLWMA-0.09.exe'

with open('test.log', 'w') as f:
p = subprocess.Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
for c in iter(lambda: p.stdout.read(1), ''):
    sys.stdout.write(c)
    f.write(c)

exe 程序有一些运行错误,我需要获取程序的输出以修复 params 文件以防止错误.

The exe program have some running errors, and I need to get the output of the program in order to fix the params file in order to prevent the errors.

问题是,通过使用上面的代码,我没有得到 exe 的完整输出(与 os.system() 命令相比).输出写入完成前弹出exe的错误信息窗口,不知道问题出在哪里.

the problem is that by using the above code I don't get the full output of the exe (when comparing to the os.system() command). the error message window of the exe pops out before the completion of the output writing, and I don't know where is the problem.

你能帮帮我吗...

推荐答案

stderr=PIPE 将错误流重定向到 p.stderr,而您并未阅读该内容(请注意,使用 p.communicate 可以获得两个流结果,但单独读取它们会导致死锁).

stderr=PIPE redirects the error stream to p.stderr, and you're not reading that (note that using p.communicate allows to get both stream results, but reading them separately can lead to deadlocks).

无论如何,如果您不关心合并两者错误流,您可以将其更改为:

Anyway, if you don't care about merging both out & err streams, you could change that to:

stderr=STDOUT

所以两者兼而有之错误使用相同的流 p.stdout

so both out & err use the same stream p.stdout

另外:不要使用shell=True,你不需要它.

Also: don't use shell=True, you don't need it.

如果这不能解决您的问题,则意味着底层程序在未刷新其输出的情况下崩溃了.输出未重定向时,输出刷新的工作方式不同,这可以解释为什么在不使用 os.system 重定向的情况下运行它时会获得更多输出(有关此问题的更多信息:强制程序在重定向时刷新其标准输出)

If that doesn't fix it in your case, it means that the underlying program crashed while not flushing its output. Output flush works differently when output is not redirected, which may explain why you get more output when running it without redirection with os.system (more about this issue: forcing a program to flush its standard output when redirected)

尚待探索的一个方法是使用 winpty,它相当于 Windows 上的 unbuffer:Windows 上的 unbuffer 程序相当于什么?.类似的东西:

One lead yet to be explored would be to use winpty which is an equivalent of unbuffer on Windows: What is the equivalent of unbuffer program on Windows?. Something like:

cmd = ["winpty.exe","-Xallow-non-tty","-Xplain","TLWMA-0.09.exe"]
p = subprocess.Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT)

这篇关于当 exe 失败时,python popen sdtout 没有获得所有输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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