+-
Python脚本在打印前打印os.system的输出
我有一个 python脚本test.py:

print "first"
import os
os.system("echo second")

在linux命令行上我执行

python test.py

返回:

first
second

然后我执行

python test.py > test.out; cat test.out

返回

second
first

如何重定向输出使得os.system调用在print语句之前打印?

最佳答案
当您输出到管道时,Python会缓冲您写入sys.stdout的输出,并在刷新后或溢出后或关闭时(程序退出时)输出.虽然它会缓冲打印调用,但系统调用直接输出到stdout,它们的输出不会被缓冲.这就是为什么你看到这样的优先权.为避免这种情况,请使用python -u:

python -u test.py > test.out; cat test.out

查看更多信息here.

编辑:解释何时刷新缓冲区.

点击查看更多相关文章

转载注明原文:Python脚本在打印前打印os.system的输出 - 乐贴网