Python:为什么打印语句和subprocess.call()输出不同步? [英] Python: why print statements and subprocess.call() output are out of sync?
问题描述
我正在运行以下代码(称为batch.py)
I am running the following piece of code (call it batch.py)
for config in keystoneConfig:
cmdlist = generate_cmd_list(config)
print ' '.join(cmdlist)
subprocess.call(cmdlist)
然后将batch.py的输出重定向到另一个文件.即
And redirecting the output of batch.py to another file. i.e.
./batch.py> output.txt
./batch.py > output.txt
但是我意识到subprocess.call()
的所有输出都在print
语句之前.为什么输出不同步?
But I realize that all the output from subprocess.call()
goes before the print
statement. Why is the output out of sync?
推荐答案
Python正在块缓冲其自身的输出,并且不会在subprocess.call()
之前刷新它,因为您将其输出重定向到了文件而不是控制台.您将需要强制行缓冲或禁用缓冲,或者在子进程调用之前手动刷新.
Python is block buffering its own output and not flushing it before subprocess.call()
, because you redirected its output to a file instead of the console; you would need to force line buffering or disable buffering, or manually flush before the subprocess call.
这篇关于Python:为什么打印语句和subprocess.call()输出不同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!