python:读取可执行文件的 stdout,破碎的流

python: reading executable's stdout, broken stream

本文关键字:破碎 stdout python 读取 可执行文件      更新时间:2023-10-16

我正在尝试从我的python脚本中读取用c ++编写的可执行文件(A)的输出。我在 Linux 工作。到目前为止,我知道的唯一方法是通过子流程库

首先我试过

p = Popen(['executable', '-arg_flag1', arg1 ...], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
print "reach here"
stdout_output = p.communicate()[0]
print stdout_output
sys.stdin.read(1)

结果挂断了我的可执行文件(CPU 使用率为 99%)和我的脚本:S:S:S此外,到达这里被打印。

之后我尝试了:

f = open ("out.txt",  'r+')
command = 'executable -arg_flag1 arg1 ... '
subprocess.call(command,  shell=True, stdout=f)
f.seek(0)
content = f.read()

这有效,但我得到一个输出,其中内容末尾的一些字符重复,甚至产生的值比预期的还要多:S

无论如何,有人可以启发我更合适的方法来做到这一点吗?

提前致谢

第一个解决方案是最好的。使用 shell=True 速度较慢,并且存在安全问题。

问题是 Popen 不会等待进程完成,因此 Python 不再让进程没有 stdout、stdin 和 stderr。导致这个过程变得疯狂。添加 p.wait() 应该可以解决问题!

此外,使用通信会浪费时间。只需做stdout_output = p.stdout.read()。你必须检查自己是否stdout_output包含任何内容,但这仍然比使用 communication()[0] 更好。