Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #38168
| From | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| Subject | Re: autoflush on/off |
| Date | 2013-02-05 01:43 -0500 |
| References | <CAOuJsMmQ55vjG_TYU2iPNHeA=b-kGX+cWa2xFDXp4j6WfQAp3Q@mail.gmail.com> <kep8as$c12$1@ger.gmane.org> <CAOuJsM=Xv-VH_Jr0jh-1ysnbFAAn8WL+dNd+23Qh+6yZXgO-cQ@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1353.1360046662.2939.python-list@python.org> (permalink) |
On 2/4/2013 7:09 PM, Jabba Laci wrote:
> 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
This could/should go in the __enter__ method. You do not need __init__ here.
>
> def __enter__(self):
> sys.stdout.flush()
> sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
This creates a new *python* object but perhaps it does something at the
OS level that does not get reversed.
> 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)
from the time module :-?
> #
> 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
In 3.3, Win7, with the regular interpreter, I get
File "<stdin>", line 5, in __enter__
File "C:\Programs\Python33\lib\os.py", line 1032, in fdopen
return io.open(fd, *args, **kwargs)
ValueError: can't have unbuffered text I/O
If I change the mode to 'wb', I get
File "C:\Programs\Python33\lib\os.py", line 1032, in fdopen
return io.open(fd, *args, **kwargs)
OSError: [Errno 9] Bad file descriptor
With IDLE, I get
File "F:\Python\mypy\tem.py", line 7, in __enter__
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
AttributeError: fileno
It looks like you should perhaps just forget about reopening and just
use sys.stdout.flush(). This works fine even on IDLE.
import sys, time
for i in range(10):
sys.stdout.write('.'); sys.stdout.flush()
time.sleep(.5)
>>>
,,,,,,,,,,
Write a write_flush function if you want, and add any of the number,
string, and sleep time as parameters if you wish.
--
Terry Jan Reedy
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: autoflush on/off Terry Reedy <tjreedy@udel.edu> - 2013-02-05 01:43 -0500
csiph-web