Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #38152
| References | <CAOuJsMmQ55vjG_TYU2iPNHeA=b-kGX+cWa2xFDXp4j6WfQAp3Q@mail.gmail.com> <kep8as$c12$1@ger.gmane.org> |
|---|---|
| From | Jabba Laci <jabba.laci@gmail.com> |
| Date | 2013-02-05 01:09 +0100 |
| Subject | Re: autoflush on/off |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1342.1360023018.2939.python-list@python.org> (permalink) |
Hi,
Thanks for the answers. I like the context manager idea but setting
the sys.stdout back to the original value doesn't work.
Example:
class Unbuff(object):
def __init__(self):
self.stdout_bak = sys.stdout
def __enter__(self):
sys.stdout.flush()
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout = self.stdout_bak
####
with Unbuff():
for i in range(5):
sys.stdout.write('.')
sleep(.5)
#
sys.stdout.write('EXIT') # provokes an error
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
Laszlo
> Write a context manager class. See Library manual, 4.11. Context Manager
> Types. The __enter__ method would be much like the above except that is
> should save the old stdout object 'oldstdout = sys.stdout' instead of
> fiddling with 'autoflush_on'. Then __exit__ would simply be 'sys.stdout =
> oldstdout'. Drop autoflush_on. Your context manager should not care about
> the existing buffering other than to restore it on exit. Saving and
> restoring the existing stdout object does that.
>
> --
> Terry Jan Reedy
>
> --
> http://mail.python.org/mailman/listinfo/python-list
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
Re: autoflush on/off Jabba Laci <jabba.laci@gmail.com> - 2013-02-05 01:09 +0100
Re: autoflush on/off Ulrich Eckhardt <ulrich.eckhardt@dominolaser.com> - 2013-02-05 09:04 +0100
Re: autoflush on/off Piet van Oostrum <piet@vanoostrum.org> - 2013-02-05 12:59 +0100
csiph-web