Search code examples
pythonbashshellunit-testingtee

Why addition of tee changes order of output


so this is structure of my files

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

runit.sh calls run.py in dir1 which in turn calls test.py.

test.py contains actual test case. Problem Im facing is when I add tee in runit.sh to capture output to file, it changes order of output. And Im not able to figure out why. Let me also put content of the files.

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"

Now when I run test using runit.sh, I get following output

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

When I remove "| tee -a somefile" from runit.sh and run, I get this output-

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

Im going mad thinking about it from yesterday but without luck.


Solution

  • It's not about tee

    Add

    sys.stdout.flush()
    

    After

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

    Simple test:

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

    With flush:

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

    Without flush:

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