[Tutor] Console output
Marcin Komorowski
marcink at ieee.org
Thu Oct 6 00:43:14 CEST 2005
----- Original Message -----
From: "Roel Schroeven" <rschroev_nospam_ml at fastmail.fm>
To: <tutor at python.org>
Sent: Wednesday, October 05, 2005 2:53 PM
Subject: Re: [Tutor] Console output
> Oliver Maunder wrote:
>> Does anyone know how I can update a line of console output without
>> creating a new line? I'm not explaning this too well, so here's an
>> example.
>>
>> When you download a file with wget, the console display looks like this:
>>
>> 14% [=======> ]
>> 344,192 16.28K/s ETA 02:19
>>
>> All the figures and the progress bar get continously updated. The only
>> way I know of sending output to the console is to use print or
>> sys.stdout.write(), but that would give me:
>> 14% [=======> ]
>> 344,192 16.28K/s ETA 02:19
>> 18% [=========> ]
>> 344,192 16.28K/s ETA 02:19
>> 20% [============> ]
>> 344,192 16.28K/s ETA 02:19
>>
>> ...and that's really not what I'm after!
>>
>> Any help and ideas would be appreciated
>
> You need to:
> - not write a newline
> - backup to the beginning of the line
>
> Simple example:
>
> import sys
> import time
>
> def progress(n):
> for i in range(n+1):
> sys.stdout.write('\r%3s%% [%s>%s]' % (i, '='*i, ' '*(n-i)))
> sys.stdout.flush()
> time.sleep(0.5)
>
> progress(60)
>
This works nicely, but do not forget that \r does not clear what you already
have on the line, so you are safe if every time you re-write the line, you
output the same number of characters, but if it is less, you will have
residual from previous line. The way around it is to output a line of
spaces that overwrites the previous line.
> No newline is written, and the program backs up to the beginning of the
> line using carriage return, '\r'. You can also put the carriage return
> at the end of the line; the difference is that the cursor will be left
> at the beginning of the line instead of at the end.
>
> It's also possible to back up using backspaces ('\b'), but then you need
> to count how many characters you wrote and use the equal amount of
> backslashes.
>
> --
> If I have been able to see further, it was only because I stood
> on the shoulders of giants. -- Isaac Newton
>
> Roel Schroeven
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list