使用 Python 从 运行 C 程序捕获标准输出
Capture stdout from a running C program with Python
我有这个 C 程序:
#include <stdio.h>
#include <Windows.h>
int main() {
for (int i=0;; i++) {
printf("%i\n",i);
Sleep(100);
}
return 0;
}
我有一个 Python 脚本试图捕获它的输出并用它做一些事情:
from subprocess import Popen, PIPE
p = Popen("a.exe", stdout=PIPE, shell=True)
print p.stdout.readline()
...它挂在最后一行,没有在屏幕上打印任何内容。
我尝试使用 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
它实际上可以读取输出,但只能在我发送 KeyboardInterrupt 时读取。 p.stdout.read(1)
行为相同。
那么,什么是做我想做的事情的有效、正确的方法?
编辑:
好吧,看来在 Windows 上是不可能的,请参阅第一个答案的评论。
正在缓冲输出,因此您需要使用iter(p.stdout.readline,"")
p = Popen("a.exe", stdout=PIPE)
for line in iter(p.stdout.readline,""):
print line
如果 sys.stdout.flush()
如果不起作用,请尝试从 c 刷新标准输出,据我所知,在写入管道时,行是块缓冲的:
int main() {
for (int i=0;; i++) {
printf("%i\n",i);
Sleep(100);
fflush(stdout);
}
return 0;
}
我很久以前做过的粗略示例。
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while process.poll() is None:
txt = process.stdout.read().decode("utf-8")
result += txt
您可以创建自己的 StringIO 来处理读取和写入等文件 io 操作。
https://docs.python.org/3/library/io.html
我没有测试下面的代码!
import io
buffer = io.StringIO()
p = Popen(["a.exe"], stdout=buffer)
运行 python 在 unbuffered mode:
python -u myprogram.py
我有这个 C 程序:
#include <stdio.h>
#include <Windows.h>
int main() {
for (int i=0;; i++) {
printf("%i\n",i);
Sleep(100);
}
return 0;
}
我有一个 Python 脚本试图捕获它的输出并用它做一些事情:
from subprocess import Popen, PIPE
p = Popen("a.exe", stdout=PIPE, shell=True)
print p.stdout.readline()
...它挂在最后一行,没有在屏幕上打印任何内容。
我尝试使用 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
它实际上可以读取输出,但只能在我发送 KeyboardInterrupt 时读取。 p.stdout.read(1)
行为相同。
那么,什么是做我想做的事情的有效、正确的方法?
编辑:
好吧,看来在 Windows 上是不可能的,请参阅第一个答案的评论。
正在缓冲输出,因此您需要使用iter(p.stdout.readline,"")
p = Popen("a.exe", stdout=PIPE)
for line in iter(p.stdout.readline,""):
print line
如果 sys.stdout.flush()
如果不起作用,请尝试从 c 刷新标准输出,据我所知,在写入管道时,行是块缓冲的:
int main() {
for (int i=0;; i++) {
printf("%i\n",i);
Sleep(100);
fflush(stdout);
}
return 0;
}
我很久以前做过的粗略示例。
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while process.poll() is None:
txt = process.stdout.read().decode("utf-8")
result += txt
您可以创建自己的 StringIO 来处理读取和写入等文件 io 操作。
https://docs.python.org/3/library/io.html
我没有测试下面的代码!
import io
buffer = io.StringIO()
p = Popen(["a.exe"], stdout=buffer)
运行 python 在 unbuffered mode:
python -u myprogram.py