autoflush on/off
Ulrich Eckhardt
ulrich.eckhardt at dominolaser.com
Tue Feb 5 03:04:26 EST 2013
Am 05.02.2013 01:09, schrieb Jabba Laci:
> I like the context manager idea
There is a helper library for constructing context managers, see
http://docs.python.org/2/library/contextlib.html. That would have made
your code even shorter.
> setting the sys.stdout back to the original value doesn't work.
[...]
> The problem is in __exit__ when sys.stdout is pointed to the old
> value. sys.stdout.write doesn't work from then on. Output:
>
> .....close failed in file object destructor:
> sys.excepthook is missing
> lost sys.stderr
Argh! Yes, the newly-created file object takes ownership of the
filedescriptor. Once done with it, it invokes close() on it, making it
unusable for the original sys.stdout.
Okay, other approach: I believe that the only function regularly called
on sys.stdout is write(). Just write a replacement that forwards the
data to the original, followed by a call to flush. If you are ambitious,
forward any other call to sys.stdout directly by catching attribute
lookup (__getattribute__) in your class.
Good luck!
Uli
More information about the Python-list
mailing list