inspired by http aspn activestate com ASPN Cookbook Python Recipe 5351

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# inspired by:
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/535141
from __future__ import with_statement
import threading
import sys
DOTS = ('.', 'o', 'O', 'o')
ROTATOR = ('|', '/', '-', '\\')
FACES = ('._.', '._o', '._O', 'o_O', 'O_O', 'O_o', 'O_.', 'o_.')
def looped_iterator(l):
while True:
for x in l:
yield x
# Implementation of Ticker class
class Ticker(threading.Thread):
def __init__(self, msg, style=FACES):
threading.Thread.__init__(self)
self.msg = msg
self.event = threading.Event()
self.indicator = looped_iterator(style)
def __enter__(self):
self.start()
def __exit__(self, ex_type, ex_value, ex_traceback):
self.event.set()
self.join()
def run(self):
while not self.event.isSet():
sys.stdout.write("\r%s %s" % (self.msg, self.indicator.next()))
sys.stdout.flush()
self.event.wait(0.2)
# Here's how we use it...
if __name__ == '__main__':
import time
with Ticker("A test"):
time.sleep(10)
with Ticker("Second test"):
time.sleep(5)
raise Exception("Bang!")