簡體   English   中英

python Popen無法捕獲程序的標准輸出。 不確定為什么

[英]python Popen does not capture program's stdout. Unsure why

我有三個程序。 第一個是僅用於測試從subprocess.Popen讀取的內容。 第二個是在c ++中使用cout / cin具有stdout和stdin的程序。 第三個是完全相同的應用程序,除了它使用printffgets

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()

程序2。

#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;
}

c ++程序#2的輸出逐字節讀取並打印到屏幕,完全符合我的期望。 以下是程序3。

#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;
}

Popen管道看不到此輸出。 實際上,如果我將其重定向到文件,則該文件將捕獲0個字節。

這是我正在進行的測試,因為我正在使用一個應用程序,該應用程序使用printffgets與程序#3相同的方式編寫,並且我正嘗試編寫python3腳本與之通信。 我事先不知道某些提示,因此必須通過雙向通訊來處理。

如何使用Popen的stdout從程序#3讀取? 優點:為什么程序2和程序3的功能如此不同?

由於未在printf()語句之后刷新緩沖區,所以我發現了一種解決方法是使用stdbuf -o0 ,強制有問題的應用程序緩沖其輸出(或在這種情況下,禁用緩沖)。 這可以解決所有相關的問題,並可以很好地解決我的問題。 謝謝響應者!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM