如何让子进程按顺序获取标准输出和标准错误?
How can I make subprocess get the stdout and stderr in order?
示例测试文件 (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
示例测试文件 (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