In console-less environments, printing raises an exception. Disabling all print statements can be a pain. This recipe allows you to leave all print statements in place.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | try:
sys.stdout.write(" ")
sys.stdout.flush()
except IOError:
class dummyStream:
''' dummyStream behaves like a stream but does nothing. '''
def __init__(self): pass
def write(self,data): pass
def read(self,data): pass
def flush(self): pass
def close(self): pass
# and now redirect all default streams to this dummyStream:
sys.stdout = dummyStream()
sys.stderr = dummyStream()
sys.stdin = dummyStream()
sys.__stdout__ = dummyStream()
sys.__stderr__ = dummyStream()
sys.__stdin__ = dummyStream()
|
When your environment does not have stdin/stdout/stderr (eg. when freezing your program with the console-less stub of cxFreeze), printing text on screen raises an exception.
It's a pain to disable all print statements in your program or have to maintain two versions of the same program.
Using this recipe, you can leave all print statements in place.
Usage example: I wrote a program (http://sebsauvage.net/webgobbler) which can run in command-line, or as a Win32 screensaver (/s). Using this recipe, the source can be packaged in a console and console-less version with no change in code.
[PS: English is not my native language. I apologize for the bad grammar.]