Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #38141
| From | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| Subject | Re: autoflush on/off |
| Date | 2013-02-04 16:13 -0500 |
| References | <CAOuJsMmQ55vjG_TYU2iPNHeA=b-kGX+cWa2xFDXp4j6WfQAp3Q@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1334.1360012468.2939.python-list@python.org> (permalink) |
On 2/4/2013 12:12 PM, Jabba Laci wrote: > Hi, > > I'd like to set autoflush on/off in my script. I have a loop that is > checking something and every 5 second I want to print a '.' (dot). I > do it with sys.stdout.write and since there is no newline, it is > buffered and not visible immediately. I have this solution to use > unbuffered output: > > autoflush_on = False > > def unbuffered(): > """Switch autoflush on.""" > global autoflush_on > # reopen stdout file descriptor with write mode > # and 0 as the buffer size (unbuffered) > if not autoflush_on: > sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) > autoflush_on = True > > I call unbuffered() once and it works well. However, when this loop is > over, I'd like to set the output back to buffered. How to do that? As > far as I remember, in Perl it was simply $| = 1 and $| = 0. Can it > also be switched back and forth in Python? 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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: autoflush on/off Terry Reedy <tjreedy@udel.edu> - 2013-02-04 16:13 -0500
csiph-web