为什么添加tee会改变输出顺序

时间:2015-12-11 09:28:53

标签: python bash shell unit-testing tee

所以这是我文件的结构

|- runit.sh
|- dir1
  |- run.py
  |- test.py

runit.sh在dir1中调用run.py,后者又调用test.py.

test.py包含实际的测试用例。问题我面临的是当我在runit.sh中添加tee来捕获输出到文件时,它会改变输出的顺序。我无法弄清楚原因。 我还要提供文件的内容。

runit.sh

tests_to_run=" dir1"

for i in $tests_to_run
do
(
        cd $i
        python run.py 2>&1
)
done | tee -a somefile

run.py

import os, sys, subprocess

mypath = os.path.abspath(os.path.dirname(__file__))

tests = [
         'test.py',
        ]

for test in tests:
    print '\n\nRunning test --- %s' % test
    args = ['python', os.path.join(mypath, test)]
    args.extend(sys.argv)
    subprocess.call(args)

test.py

print "this is hello from test1"

现在,当我使用runit.sh运行测试时,我得到以下输出

this is hello from test1
Running test --- test.py

当我从runit.sh中删除“| tee -a somefile”并运行时,我得到了这个输出 -

Running test --- test.py
this is hello from test1
我从昨天开始疯狂思考,但没有运气。

1 个答案:

答案 0 :(得分:3)

不是tee

添加

sys.stdout.flush()

之后

print '\n\nRunning test --- %s' % test

简单测试:

:/tmp/test/dir1 $ python run.py
Running test --- test.py
this is hello from test1

使用flush:

:/tmp/test/dir1 $ python run.py | xargs
Running test --- test.py this is hello from test1

没有同花顺:

:/tmp/test/dir1 $ python run.py | xargs
this is hello from test1 Running test --- test.py