我有一个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调用打印?
我有一个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调用打印?
当你输出到一个管道,Python的缓存形式,它以你的输出sys.stdout
和冲洗后,输出它,或者它飞越后,或在关闭(在程序退出时)。 虽然它会缓冲打印通话,系统调用输出直接进入stdout和它们的输出不会被缓冲。 这就是为什么你看到这样的优先级。 为了避免这种情况,使用python -u
:
python -u test.py > test.out; cat test.out
查看更多的信息在这里 。
编辑 :当缓冲器被刷上的解释。
以防止OS缓冲另一种方式是冲洗第一打印后的输出:
#!/usr/bin/env python
import sys
print "first"
sys.stdout.flush()
import os
os.system("echo second")
当Python脚本的输出是一个tty,其输出行缓冲。 当输出是一个普通文件,输出是块缓冲。