Python: Subprocess.popen stdout: 不在实时缓冲区中

Python: Subprocess.popen stdout: not in real time buffer

我花了很长时间才在子进程 中实时捕获 python scrypt 的标准输出

解决方案

main.py

import subprocess
import io
import time
import sys

if __name__ == '__main__':

    command = ["python", "-u", "createValue.py"] # "-u" changed my life

    p = subprocess.Popen(command,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)

    for line in iter(p.stdout.readline, b''):
        print(">>> " + str(line.rstrip()))

createValue.py


import time
import sys

i = 0

while i < 5:

    print("I like pizza "+ str(i))
    # sys.stdout.flush() # This is an another solution
    time.sleep(1.5)

    i += 1

为什么 Internet 上的每个解决方案都可以在没有“-u”的情况下工作,但在我的 PC 上却不行? 我用的是Python 3.6.5

是的,因为你需要添加一个名为PYTHONUNBUFFERED的环境变量并将其设置为= 1

"...将 PYTHONUNBUFFERED 设置为非空值可确保 python 输出直接发送到终端..."

使用您的代码检查以下解决方案:

import os # Added this line
import subprocess
import io
import time
import sys

if __name__ == '__main__':
    os.environ["PYTHONUNBUFFERED"] = "1" # Added
    command = ["python", "createValue.py"] # Removed "-u"

    p = subprocess.Popen(command,  
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
    print("init")
    for line in iter(p.stdout.readline, b''):
        print(">>> " + str(line.rstrip()))