[Tutor] Writing to the terminal?

Steven D'Aprano steve at pearwood.info
Fri Dec 10 21:51:14 CET 2010


Modulok wrote:
> List,
> 
> Forgive me if I don't describe this well, I'm new to it:

[snip description of a progress bar]

Here's one way:

import time, sys
f = sys.stdout
for i in range(20):
     time.sleep(1)  # do some work
     f.write('=')
     f.flush()  # make the change visible immediately
else:
     f.write('\n')


You might be able to get the same effect with print, but it's probably 
easier using sys.stdout directly.

Here's another way, which *must* use stdout and not print.

for i in range(20):
     percentage = i/20.0
     spinner = '/-\\-'[i % 4]
     f.write("Progress: %5.2f%% %s %s>\r" %
             (percentage, spinner, '='*(i+1)))
     f.flush()
     time.sleep(1)
else:
     f.write('\n')





-- 
Steven



More information about the Tutor mailing list