【问题标题】:Python script prints output of os.system before printPython 脚本在打印之前打印 os.system 的输出
【发布时间】:2013-03-21 19:21:26
【问题描述】:
我有一个 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 在 print 语句之前呢??
【问题讨论】:
标签:
python
linux
command-line
stdout
【解决方案1】:
当您输出到管道时,Python 会缓冲您写入 sys.stdout 的输出,并在刷新后、溢出后或关闭时(程序退出时)输出。虽然它会缓冲打印调用,但系统调用直接输出到标准输出,并且它们的输出不会被缓冲。这就是为什么你会看到这样的优先级。为避免这种情况,请使用python -u:
python -u test.py > test.out; cat test.out
查看更多信息here。
编辑:解释何时刷新缓冲区。
【解决方案2】:
防止操作系统缓冲的另一种方法是在第一次打印后刷新输出:
#!/usr/bin/env python
import sys
print "first"
sys.stdout.flush()
import os
os.system("echo second")
【解决方案3】:
当 python 脚本的输出是 tty 时,它的输出是行缓冲的。当输出是常规文件时,输出是块缓冲的。