Python标准输出和子进程

时间:2013-08-06 02:21:17

标签: python unix

我有两个文件:

run.py

import subprocess
import time

while True:
  time.sleep(1)
  print 'hello'
  proc = subprocess.call(['./writer.sh'])

writer.sh(chmod 777'd)

#!/bin/sh
echo 'write something here'

我对以下输出感到困惑:

$ python run.py
hello
write something here
hello
write something here
hello
write something here
....

$ python run.py | tee out.log
write something here
write something here
(hello disappears)

....

$ python run.py > out.log
# Nothing, but out.log has the following:
write something here
write something here
write something here
write something here
hello
hello
hello
hello
... # and the two basically "expand" the longer I run this (instead of appending)

发生了什么,如何像第一个命令一样输出所有内容?

1 个答案:

答案 0 :(得分:2)

主脚本的输出被缓冲。在运行子流程之前立即调用sys.stdout.flush()