Reputation: 9044
I have a simply script which print some 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 order in output,
[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()
can solve the problem, is there a way to force the message sequence (to redirect the output/error to a file) without changing the script?
Upvotes: 4
Views: 110
Reputation: 487963
You can run python with the -u flag to force stdin, stdout, and stderr to be unbuffered. There is a performance penalty for doing so. It's better to do explicit .flush() operations at any point that you intend everything to be "visible immediately", both because it's more efficient, and because it makes your intent obvious ("this should be visible immediately!").
Upvotes: 4