Python脚本在打印之前打印os.system的输出 [英] Python script prints output of os.system before print
问题描述
我有一个python脚本test.py:
I have a python script test.py:
print "first"
import os
os.system("echo second")
我在linux命令行上执行
On linux command line I execute
python test.py
返回:
first
second
然后我执行
python test.py > test.out; cat test.out
返回
second
first
如何重定向输出使os.system调用在print语句之前打印?
What about redirecting the output makes the os.system call print before the print statement??
推荐答案
在输出到管道时,Python缓冲写入sys.stdout
的输出,并在刷新,溢出或之后将其输出关闭(程序退出时).虽然它将缓冲打印调用,但系统调用输出将直接输出到stdout中,并且其输出将不会被缓冲.这就是为什么您会看到这样的优先级.为避免这种情况,请使用python -u
:
When you're outputting to a pipe, Python buffers your output that's written to sys.stdout
and outputs it after a flush, or after it's overflown, or upon closing (when the program exits). While it'll buffer the print calls, system calls output directly into stdout and their output won't be buffered. That's why you're seeing such precedence. To avoid that, use python -u
:
python -u test.py > test.out; cat test.out
在此处查看更多信息.
EDIT :有关何时刷新缓冲区的说明.
EDIT: explanation on when the buffer will be flushed.
这篇关于Python脚本在打印之前打印os.system的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!