sleep() function, perhaps.

Peter Otten __peter__ at web.de
Tue Nov 25 13:06:32 EST 2003


Peter Hansen wrote:

> And a quicky OO version for kicks (untested):
> 
> class Spinner:
>     CHARS = r"|/-\"

Python chokes when it encounters an odd number of backslashes at the end of
a raw string.

>     def __init__(self, stream=sys.stdout):
>         self.index = 0
>         self.stream = stream
>     def spin(self):
>         self.stream.write('\r' + self.CHARS[self.index])
>         self.stream.flush()
>         self.index = (self.index + 1) % len(CHARS)

Whenever you have to calculate an index, look into the itertools module
first; so here's my variant (2.3 only):

class Spinner:
    def __init__(self, stream=sys.stdout, chars="|/-\\"):
        self.cycle = itertools.cycle(["\r" + c for c in chars])
        self.stream = stream
    def spin(self):
        self.stream.write(self.cycle.next())
        self.stream.flush()

Peter




More information about the Python-list mailing list