[英]Python - How to read from long-running subprocess?
Reading from a long-running subprocess seems to be possible, but I can only get it to work if the subprocess is python3 -i
:从长时间运行的子进程中读取似乎是可能的,但如果子进程是
python3 -i
,我只能让它工作:
>>> sub = subprocess.Popen(['python3', '-i'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> sub.stdin.write(b'2+3\n')
4
>>> sub.stdin.flush()
>>> sub.stdout.readline()
b'5\n'
Attempting the same thing with a small echo program does not work:用一个小的 echo 程序尝试同样的事情是行不通的:
>>> sub = subprocess.Popen(['./echo'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> sub.stdin.write(b'2+3\n')
4
>>> sub.stdin.flush()
>>> sub.stdout.readline()
^ Hangs here until interrupted with Ctrl-C
echo
reads from STDIO and echoes when it gets a newline. echo
从 STDIO 读取并在换行时echo
。 It works fine when run directly.直接运行时效果很好。 Here is the code for it:
这是它的代码:
#include <iostream>
#include <unistd.h>
int main() {
char message[64];
uint8_t cursor = 0;
while(true) {
read(STDIN_FILENO, message + cursor, 1);
if(message[cursor++] == '\n') {
message[cursor] = 0;
printf(message);
cursor = 0;
}
}
}
I've tried a few other techniques like .communicate()
with similar results.我尝试了一些其他技术,如
.communicate()
,结果相似。 Oddly, subprocess.Popen(['python3'], ...)
fails where the same call works when running python3 -i
, even though python3
and python3 -i
seem to do the same thing when run at the terminal.奇怪的是,
subprocess.Popen(['python3'], ...)
在运行python3 -i
时相同的调用工作失败,即使python3
和python3 -i
在终端运行时似乎做同样的事情。
The issue turned out to be buffering within the subprocess' stdout.问题原来是在子进程的标准输出中缓冲。 I solved it by setting line-buffering using
setvbuf (stdout, NULL, _IOLBF, 1024);
我通过使用
setvbuf (stdout, NULL, _IOLBF, 1024);
设置行缓冲来解决它setvbuf (stdout, NULL, _IOLBF, 1024);
. . If no buffering at all is desired,
setvbuf (stdout, NULL, _IONBF, 0);
如果根本不需要缓冲,则
setvbuf (stdout, NULL, _IONBF, 0);
can be used.可以使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.