CuriousMind
CuriousMind

Reputation: 15808

Python: why print statements and subprocess.call() output are out of sync?

I am running the following piece of code (call it batch.py)

for config in keystoneConfig: 
    cmdlist = generate_cmd_list(config)
    print ' '.join(cmdlist)
    subprocess.call(cmdlist)

And redirecting the output of batch.py to another file. i.e.

./batch.py > output.txt

But I realize that all the output from subprocess.call() goes before the print statement. Why is the output out of sync?

Upvotes: 5

Views: 1731

Answers (2)

db 1070
db 1070

Reputation: 51

Flush with sys.stdout.flush() after printing and before making the subprocess call.

Upvotes: 5

geekosaur
geekosaur

Reputation: 61459

Python is block buffering its own output and not flushing it before subprocess.call(), because you redirected its output to a file instead of the console; you would need to force line buffering or disable buffering, or manually flush before the subprocess call.

Upvotes: 10

Related Questions