当我编写一个名为external.py的python脚本时
p = subprocess.Popen(['./inner.py'])
print('Called inner.py without options, waiting for process...')
p.wait()
print('Waited for inner.py without options')
p = subprocess.Popen(['./inner.py'], stdout=subprocess.PIPE)
print('Called inner.py with PIPE, communicating...')
b_out, b_err = p.communicate()
out = b_out.decode('utf8')
print('out is "{}"'.format(out))
还有一个inner.py包含
print("inner: Echoing Hallo")
p = subprocess.Popen(['echo', 'hallo'])
print("inner: Waiting for Echo to finish...")
p.wait()
print("inner: Waited for Echo")
从终端调用external.py时,我得到以下信息:
Called inner.py without options, waiting for process...
inner: Echoing Hallo
inner: Waiting for Echo to finish...
hallo
inner: Waited for Echo
Waited for inner.py without options
Called inner.py with PIPE, communicating...
out is "hallo
inner: Echoing Hallo
inner: Waiting for Echo to finish...
inner: Waited for Echo
"
为什么在使用stdout = subprocess.PIPE调用inner.py时,捕获的输出中“ hallo”出现在“ inner:Echoing Hallo”之前?
解决方法:
我会猜测,由于某种原因(与管道与ttys有关,请参见this comment),inner.py Python进程的输出在第一次调用时是未缓冲的,而在第二次调用时是缓冲的.第一次使用无缓冲输出时,您将获得按预期顺序写入tty的结果.第二次使用缓冲,首先刷新echo命令的输出(因为echo运行并终止),然后在python终止时立即显示inner.py进程的所有输出.如果为inner.py禁用输出缓冲,则在两种情况下都应获得相同的输出.
通过设置PYTHONUNBUFFERED环境变量或通过使用-u开关调用python,或在每次打印后显式调用sys.stdout.flush()(在Python 3上为print(…,flush = True))来禁用输出缓冲. .
管道和ttys的行为之间的差异似乎是general behaviour of stdio
:ttys的输出是行缓冲的(因此,在您的代码中,它逐行读取,似乎是没有缓冲的),而管道的输出则是缓冲的.