【发布时间】:2021-09-03 06:59:03
【问题描述】:
为了在子进程中实时捕获 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
【问题讨论】:
-
AFAIK,-u 表示无缓冲,意思是:Python 不会缓冲输出,它会在数据指向 stdout 时立即将其发回。这不是你想要的吗?我没有发现您的代码有任何问题。
-
是的,它可以在没有“-u”的情况下实时工作吗?互联网上的每个解决方案都不使用“-u” 示例1:stackoverflow.com/questions/1606795/… 示例2:stackoverflow.com/questions/18421757/…
标签: python subprocess buffer real-time stdout