示例测试文件 (print.py):
import sys
print('stdout')
print('stderr', file=sys.stderr)
运行它的代码 (x.py):
import subprocess
cmd = ['python', 'print.py']
print(subprocess.check_output(cmd, universal_newlines=True, stderr=subprocess.STDOUT))
如果我从 shell 运行 print.py,它会首先打印标准输出。但是,如果我运行 x.py,它会先打印 stderr。有什么方法可以按正确的顺序获取输出吗?
您的代码正在缓冲(即延迟)其输出。缓冲过程的详细信息因输出是控制台还是管道而异。
试试这个:
cmd = ['python', '-u', 'print.py']
参考:https://docs.python.org/3.5/using/cmdline.html#cmdoption-u