python Popen无法捕获程序的标准输出。不确定为什么

时间:2018-12-19 04:51:12

标签: python popen

我有三个程序。第一个是仅用于测试从jsonValue#读取的内容。第二个是在c ++中使用subprocess.Popen / cout具有stdout和stdin的程序。第三个是完全相同的应用程序,除了它使用cinprintf

fgets

程序2。

import subprocess
import shlex
import os


def main():
    proc = subprocess.Popen(
        shlex.split('/home/art/dlm/test1'),
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    data = b''
    old_len = 0
    while True:
        print('Progress 1')
        data += proc.stdout.read(1)
        print('Progress 2')
        if old_len == len(data):
            break
        old_len = len(data)
        print(data)
    print('Progress 3')


if __name__ == '__main__':
    main()

c ++程序2的输出逐字节读取并打印到屏幕上,完全符合我的期望。以下是程序#3。

#include <iostream>

using namespace std;

int main() {
    char _input[100];
    cout << "Line 1 test" << endl;
    cout << "Line 1 test" << endl;
    cout << "Line 3 test" << endl;
    cout << "Thoughts? ";
    cin >> _input;
    cout << _input << endl;
    return 1;
}

#include <iostream> #include <stdio.h> using namespace std; int main() { char _input[100]; /*cout << "Line 1 test" << endl; cout << "Line 2 test" << endl; cout << "Line 3 test" << endl; cout << "Thoughts? ";*/ printf("Line 1 test\n"); printf("Line 2 test\n"); printf("Line 3 input: "); fgets(_input, sizeof(_input), stdin); printf("Line 4 test: %s\n", _input); //cin >> _input; //cout << _input << endl; return 1; } 管道看不到此输出。实际上,如果我将其重定向到文件,则该文件将捕获0个字节。

这是我正在进行的测试,因为我有一个正在使用Popenprintf编写与程序#3相同的应用程序,而我正在尝试编写python3脚本与之沟通。我事先不知道某些提示,因此必须通过双向通讯来处理。

如何使用fgets的标准输出从程序#3中读取?优点:为什么程序2和程序3的功能如此不同?

1 个答案:

答案 0 :(得分:0)

由于在printf()语句之后未刷新缓冲区,因此我发现了一种解决方法是使用stdbuf -o0,从而迫使有问题的应用程序缓冲其输出(或者在这种情况下,禁用缓冲)。这可以解决所有相关的问题,并可以很好地解决我的问题。谢谢响应者!

相关问题