【问题标题】:I want to get subprocess's output while it is still running, but it is always block我想在子进程仍在运行时获取它的输出,但它总是阻塞
【发布时间】:2019-01-15 07:30:49
【问题描述】:

我有一个c程序,输入为stdin,输出为stderr,我想在它还在运行的时候得到它的输出,但它总是阻塞,我该怎么办?

这是python代码

i = 0
popen1 = subprocess.Popen(['./hello1'], stdin=subprocess.PIPE, 
stderr=subprocess.PIPE, universal_newlines=True)
while i < 30:
    if popen1.poll() is None:
        popen1.stdin.write("ada\n")
        print("write line......")
        #print(popen1.stderr)
        for stderr_line in popen1.stderr:
            print(stderr_line, end="")
            sys.stderr.flush()
    i += 1

这是c代码:

int main(int argc, char *argv[]){
    int i = 0;
    char str[20];
    while(i < 30){
        scanf("%s", str);
        fprintf(stderr, "%s\n", str);
        fprintf(stderr, "%s\n", argv[0]);
        i++;
    }
    //while(1);
}

实际结果是

write line......
<_io.TextIOWrapper name=5 encoding='UTF-8'>

然后它会阻塞

【问题讨论】:

  • 但在 python 中,我已将输入添加到 stdin@ƘɌỈSƬƠƑ

标签: python-3.x subprocess


【解决方案1】:

目前,您正在打印对stderr 的引用。此外,您正在刷新sys.stderr,但那里没有数据,因为您正在打印到sys.stdout

我会将for 循环更改为:

for stderr_line in popen1.stderr.read():
    print(stderr_line, end='', flush=True)

【讨论】:

  • 很抱歉还是不行,我觉得flush可能不是这个原因。
  • 你删除了sys.stderr.flush()吗?
猜你喜欢
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-06
  • 1970-01-01
  • 1970-01-01
  • 2016-03-14
  • 2016-06-21
相关资源
最近更新 更多