Problems with sys.stout.flush()

Joel Ross joelc at cognyx.com
Sat May 23 05:20:47 EDT 2009


Carl Banks wrote:
> On May 22, 10:33 pm, Joel Ross <jo... at cognyx.com> wrote:
>> Hi all,
>>
>> I'm using python 2.5 and trying to flush the sys.stout buffer with
>> sys.stout.flush(), but doesn't seem to work. Each time a line is printed
>>    it appends the one before it I need to clear the output and write a
>> new output without appending the previous one.
> 
> That's not how streams work, chief.  Once you output (and flush)
> something you can't un-output it.
> 
> What you probably want to do is to write a carriage return ("\r")
> which usually causes the cursor to return to the beginning of the
> line, so that any new text you write overwrites the old text.
> 
> This has nothing to do with flushing; flushing doesn't erase or clear
> the old input.  Flushing is usually needed for a different reason,
> however, namely standard output doesn't actually get sent to the
> console until it sees a newline ("\n") unless you flush the buffer.
> 
> Try to adapt this example to your problem:
> 
> for i in xrange(11):
>     sys.stdout.write('*'*(10-i) + ' '*i + '\r')
>     sys.stdout.flush()
>     time.sleep(2)
> 
Your example prints a new line each time, Doesn't help me with a 
progress bar, do you know of anyway doing it with the print command? My 
progress bars works fine this is the only problem im having with it at 
the moment. any help would be appreciated.

cheers
> 
> Notice that you have to print out spaces as well, to overwrite the
> previous characters on the line (well, it might not be strictly needed
> for a progress bar that only grows, but it's normally a good idea.
> 
> 
>> I have tried the -u
>> (unbuffered) option for python and a few examples from this sitehttp://stackoverflow.com/questions/107705/python-output-buffering
>>
>> Code:
>>
>> import sys
>> from time import sleep
>>
>> def progress(number, total,  char):
>>
>>      percentage = float(number*100)/total
>>      percentage = int(round(percentage))
>>      percentage = int(100 - percentage)
>>      if percentage > 0:
>>          char = char * percentage
>>          sys.stdout.write(char)
>>          sys.stdout.flush()      #Not working correctly
>>          sleep(2)
>>
>> progress(40, 50, "*")
>> progress(30, 50, "*")
>> progress(20, 50, "*")
>> progress(10, 50, "*")
>> progress(2, 50, "*")
>>
>> Regards
>>
>> jross
> 
> 
> 
> Carl Banks



More information about the Python-list mailing list