python中os.system.获取输出信息,Python脚本在打印之前打印os.system的输出

本文探讨了Python脚本中print语句与os.system调用的输出顺序问题。在标准输出被重定向时,由于Python对sys.stdout进行了缓冲,导致os.system直接输出到stdout而不受缓冲影响,从而改变了输出顺序。通过使用python -u选项可以解决此问题。
摘要由CSDN通过智能技术生成

I have a python script test.py:

print "first"

import os

os.system("echo second")

On linux command line I execute

python test.py

which returns:

first

second

I then execute

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

which returns

second

first

What about redirecting the output makes the os.system call print before the print statement??

解决方案

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

See more info here.

EDIT: explanation on when the buffer will be flushed.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值