Strange io redirect behavior

I have just a script that prints some kind of message to the console,

#!/usr/bin/python import sys print >>sys.stdout, "1 stdout" print >>sys.stderr, "2 stderr" 

normal sequence

 [ dyno@cola :codes]$ ./x.py 1 stdout 2 stderr [ dyno@cola :codes]$ ./x.py 2>&1 1 stdout 2 stderr 

wrong output order

 [ dyno@cola :codes]$ ./x.py &>x.txt [ dyno@cola :codes]$ cat x.txt 2 stderr 1 stdout [ dyno@cola :codes]$ ./x.py 2>&1 | tee x.log 2 stderr 1 stdout 

It seems that adding sys.stdout.flush() might solve the problem, is there a way to force the message sequence (redirect the output / error to a file) without changing the script?

+4
source share
1 answer

You can run python with the -u flag to force stdin, stdout and stderr to be unbuffered. There is a penalty for execution for this. It is better to do explicit .flush () operations at any time when you intend for everything to be "visible immediately", both because it is more efficient and because it makes your intention obvious ("it should be immediately visible!" )

+4
source

Source: https://habr.com/ru/post/1400361/


All Articles