Redirecting stdout from a python script called in *nix environment does not work correctly Redirecting stdout from a python script called in *nix environment does not work correctly unix unix

Redirecting stdout from a python script called in *nix environment does not work correctly


You can run python with unbuffered output using the command line switch -u, i.e. you can just call python -u myscript.py and the output to stdout should be synchronized thereafter.


Python uses line-buffering when stdout is a tty device, hence the output is as per print statements order. In case of redirection python buffers the output of print statements. While c++ executable output buffering is not handled by python in both cases. So when the output is redirected, the print statements are getting buffered and doesn't output to file till the buffer is full or program ends.

sys.stdout.flush() will flush the output of print statements as below. Note it should follow the print statements

#!/usr/local/bin/pythonimport osimport sysprint("Hello1")print("Hello2")sys.stdout.flush()os.system("/python/cppprog.o")print("Bye1")print("Bye2")

Output:

]# python script.py > o.txt]# cat o.txtHello1Hello2Hello, world!Bye1Bye2


This is because python's stdout buffer and os' stdout buffer are not synced.

Try flushing stdout after your print statements and before executing c++ executables.

import syssys.stdout.flush()