python:读取可执行文件的 stdout,破碎的流
python: reading executable's stdout, broken stream
我正在尝试从我的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] 更好。
相关文章:
- 如何将stdout重定向到stderr
- MacOS通过在莫哈韦"wchar.h"下破碎的自制啤酒发出叮当声
- C++|以一种很好的方式将树(不一定是二进制的)打印到stdout
- 是否可以将子进程的 stdout 重定向到父进程中的另一个文件?
- 尝试在 Windows 上重定向 stdout 和 stderr——_fileno(stdout) 返回 -2
- pybind11将python sys.stdout从print()重定向到c++
- 当使用带有stdin和stdout重定向的双进程管道时,如何避免stdin上的重复输入
- 如何将控制台(stdout)添加为g3log中的接收器
- CreateProcess stdout with CreateNamedPipe Overlapped
- 使用参数 + stdout + stderr 从命令行调用 MFC 应用程序
- visual Redirect stdout/stderr to null vs2017 c++
- fprintf stdout 没有 100% 准确转储数据
- 如何将"cout"、"cerr"、"stdout"和"stderr"从C++程序定向到单个文件
- 写入 /dev/stdout 的程序:如何发送 EOF?
- 为什么PNG图像的stdout有时会在printf中刷新图像的一半
- stdin,stdout,stderr是如何关闭的
- 为什么我在C 代码的Stdout上得到响应
- 通过stdin/stdout和qdatastream与Qprocess进行通信
- 在Stdout上似乎是僵局
- python:读取可执行文件的 stdout,破碎的流