Terminal application with non-standard print

Grant Edwards invalid at invalid.invalid
Mon Jan 25 17:20:54 EST 2010


On 2010-01-25, Hans Mulder <hansmu at xs4all.nl> wrote:
> Grant Edwards wrote:
>> On 2010-01-24, R?mi <babedoudi at yahoo.fr> wrote:
>> 
>>> I would like to do a Python application that prints data to stdout, but
>>> not the common way. I do not want the lines to be printed after each
>>> other, but the old lines to be replaced with the new ones, like wget
>>> does it for example (when downloading a file you can see the percentage
>>> increasing on a same line).
>> 
>> sys.stdout.write("Here's the first line")
>> time.sleep(1)
>> sys.stdout.write("\rAnd this line replaces it.")
>
> That does not work on my system, because sys.stdout is line buffered.

That's correct of course.

> This causes both strings to be written when sys.stdout is closed because
> Python is shutting down.
>
> This works better:
>
>      import sys, time
>
>      sys.stdout.write("Here's the first line")
>      sys.stdout.flush()
>      time.sleep(1)
>      sys.stdout.write("\rAnd this line replaces it.")
>      sys.stdout.flush()

Or you can tell Python to do unbuffered output:

#!/usr/bin/python -u

-- 
Grant Edwards                   grante             Yow! I'm using my X-RAY
                                  at               VISION to obtain a rare
                               visi.com            glimpse of the INNER
                                                   WORKINGS of this POTATO!!



More information about the Python-list mailing list