How to better control print and stdout?

Peter Hansen peter at engcorp.com
Sat Mar 15 00:54:23 CET 2003


Drew Smathers wrote:
> 
> Basically, all I want to do is be able to make nice 
> countdowns, or the classic spinner (|,/,-,\), using the escape 
> code '\b'.
> Is there anyway to get around this without using any fancy libs like ncurses?

Based on Erik Max's suggestions:


import sys, time

def output(char):
    sys.stdout.write(char)
    sys.stdout.flush()

def spinner(rotations, interval):
    symbols = '|/-\\'
    for x in xrange(rotations):
        for ch in symbols:
            output(ch + '\b')
            time.sleep(interval)
    output(' \n')

if __name__ == '__main__':
    spinner(int(sys.argv[1]), float(sys.argv[2]))

c:\> python spins.py 55 .05

(outputs |/-\ etc....)


-Peter




More information about the Python-list mailing list