且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么子进程的管道输出对Python如此不可靠?

更新时间:2023-02-09 22:51:58

根据与此密切相关的线程:

As per this closely related thread: Unbuffered read from process using subprocess in Python

process = subprocess.Popen('sox_call_dummy.bat', 
                stderr = subprocess.PIPE, bufsize=0)
while True:
    line = process.stderr.readline()
    if not line: 
        break
    print line

由于您没有阅读stdout,所以我认为您不需要管道.

Since you aren't reading stdout, I don't think you need a pipe for it.

如果您要尝试像原始示例一样逐个读取char,请尝试每次添加一次刷新:

If you want to try reading char by char as in your original example, try adding a flush each time:

sys.stdout.write(char)
sys.stdout.flush()

每次编写时刷新标准输出都是手动禁用python进程的缓冲:python.exe -u <script>或设置env变量PYTHONUNBUFFERED=1

Flushing the stdout every time you write is the manual equivalent of disabling buffering for the python process: python.exe -u <script> or setting the env variable PYTHONUNBUFFERED=1