[英]Capture stdout from a running C program with Python
I've got this C program: 我有这个C程序:
#include <stdio.h>
#include <Windows.h>
int main() {
for (int i=0;; i++) {
printf("%i\n",i);
Sleep(100);
}
return 0;
}
And I have a Python script that tries to capture its output and do something with it: 我有一个Python脚本试图捕获其输出并对其进行处理:
from subprocess import Popen, PIPE
p = Popen("a.exe", stdout=PIPE, shell=True)
print p.stdout.readline()
... and it hangs on the last line without printing anything on a screen. ...,它挂在最后一行,而没有在屏幕上打印任何内容。
I've tried to solve this problem using the Python shell and found this: 我尝试使用Python Shell解决此问题,并发现了这一点:
>>> from test import *
>>> p.stdout.flush()
>>> p.stdout.readline()
'0\r\n'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
^CKeyboardInterrupt
It can actually read the output but only when I send KeyboardInterrupt. 它实际上可以读取输出,但仅当我发送KeyboardInterrupt时才可以。
p.stdout.read(1)
behaves the same way. p.stdout.read(1)
行为相同。
So, what's a working, correct way to do what I want? 那么,什么是可行的,正确的方法来做我想要的?
Edit: 编辑:
Ok, looks like it is impossible on Windows, see comments to first answer. 好的,看起来在Windows上是不可能的,请参阅注释以获取第一个答案。
The output is being buffered so you need to use iter(p.stdout.readline,"")
输出正在缓冲,因此您需要使用
iter(p.stdout.readline,"")
p = Popen("a.exe", stdout=PIPE)
for line in iter(p.stdout.readline,""):
print line
Try flushing stdout from c if sys.stdout.flush()
if is not working, as far as I know lines are block buffered when writing to a pipe: 据我所知,如果
sys.stdout.flush()
无法正常工作,请尝试从c刷新stdout,据我所知,写入管道时会阻塞行:
int main() {
for (int i=0;; i++) {
printf("%i\n",i);
Sleep(100);
fflush(stdout);
}
return 0;
}
Rough example of something I did a long time ago. 我很久以前做过的一个粗糙的例子。
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while process.poll() is None:
txt = process.stdout.read().decode("utf-8")
result += txt
You can make your own StringIO which handles file io operations like read and write. 您可以创建自己的StringIO来处理文件io操作(例如读写)。
https://docs.python.org/3/library/io.html https://docs.python.org/3/library/io.html
I have not tested the code below! 我还没有测试下面的代码!
import io
buffer = io.StringIO()
p = Popen(["a.exe"], stdout=buffer)
以无缓冲模式运行python:
python -u myprogram.py
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.