Is there any way to get the effect of running python -u from within my code? Failing that, can my program check if it is running in -u mode and exit with an error message if not? This is on linux (ubuntu 8.10 server)
+1
A:
Assuming you're on Windows:
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
RichieHindle
2009-05-19 09:18:25
sorry, forgot to add that. on linux (ubuntu)
Martin DeMello
2009-05-19 10:27:13
@Martin DeMello: Please do not add new facts in comments. Please update your question with new facts. New facts in comments are hard to find.
S.Lott
2009-05-19 10:37:19
done. sorry about that.
Martin DeMello
2009-05-19 10:39:00
+2
A:
I think this question has already been answered on SO:
import sys
sys.stdout.flush()
(Although you probably want to do this without constantly flushing sys.stdout?)
biocs
2009-05-19 10:31:22
yep, i want to autoflush stdout when there's stuff written. python -u does it, for instance.
Martin DeMello
2009-05-19 10:39:39
okay, the 'custom stdout object' solution in that thread looks like it should work
Martin DeMello
2009-05-19 10:48:05
+1
A:
You might use the fact that stderr is never buffered and try to redirect stdout to stderr:
import sys
#buffered output is here
doStuff()
oldStdout = sys.stdout
sys.stdout = sys.stderr
#unbuffered output from here on
doMoreStuff()
sys.stdout = oldStdout
#the output is buffered again
doEvenMoreStuff()
bgbg
2009-05-19 10:51:03
a hack, but a very cute one :) doesn't really work if you need your stderr separate but nice idea
Martin DeMello
2009-05-20 07:21:25
+5
A:
The best I could come up with:
>>> import os
>>> import sys
>>> unbuffered = os.fdopen(sys.stdout.fileno(), 'w', 0)
>>> unbuffered.write('test')
test>>>
>>> sys.stdout = unbuffered
>>> print 'test'
test
Tested on GNU/Linux. It seems it should work on Windows too. If I knew how to reopen sys.stdout, it would be much easier:
sys.stdout = open('???', 'w', 0)
References:
http://docs.python.org/library/stdtypes.html#file-objects
http://docs.python.org/library/functions.html#open
http://docs.python.org/library/os.html#file-object-creation
[Edit]
Note that it would be probably better to close sys.stdout before overwriting it.
Bastien Léonard
2009-05-19 10:51:10
+2
A:
You could always pass the -u parameter in the shebang line:
#!/usr/bin/python -u
threecheeseopera
2010-07-29 20:29:04