Problems with sys.stout.flush()

Carl Banks pavlovevidence at gmail.com
Sat May 23 07:57:24 EDT 2009


On May 23, 3:49 am, Joel Ross <jo... at cognyx.com> wrote:
>      def progressbar(self, number, total,  char):
>
>          percentage = float(number*100)/total
>          percentage = int(round(percentage))
>          percentage = int(100 - percentage)
>          self.f=sys.stdout
>          if percentage > 0:
>              char = char * percentage
>              self.f.write(char)
>              self.f.flush()            
>              sleep(0.2)
[snip]
> So when it prints a progress at 50% it will print 50 (*) characters and
> if the next progress is 51% it will print 51 (*) characters including
> the last 50 (*) characters, so instead on ending up with 100 (*)
> characters I end up with a shit load of them depending on how many lines
> I pass to the progressbar() function.

Here's why: when you write "char = char * percentage", you are setting
char to a string, so on the next iteration char is the string you
printed last time.  Thus char grows factorially with iterations.  Not
good.

Instead, change char to some other name so you don't ever overwrite
it; char should always be just one character.

             bar = char * percentage
             self.f.write(bar)


Carl Banks



More information about the Python-list mailing list