A console spin cursor class
| 4 | import unicodedata |
| 5 | |
| 6 | class SpinCursor(threading.Thread): |
| 7 | """ A console spin cursor class """ |
| 8 | |
| 9 | def __init__(self, msg='',maxspin=0,minspin=10,speed=5): |
| 10 | # Count of a spin |
| 11 | self.count = 0 |
| 12 | self.out = sys.stdout |
| 13 | self.flag = False |
| 14 | self.max = maxspin |
| 15 | self.min = minspin |
| 16 | # Any message to print first ? |
| 17 | self.msg = msg |
| 18 | # Complete printed string |
| 19 | self.string = '' |
| 20 | # Speed is given as number of spins a second |
| 21 | # Use it to calculate spin wait time |
| 22 | self.waittime = 1.0/float(speed*4) |
| 23 | if os.name == 'posix': |
| 24 | self.spinchars = (unicodedata.lookup('FIGURE DASH'),u'\\ ',u'| ',u'/ ') |
| 25 | else: |
| 26 | # The unicode dash character does not show |
| 27 | # up properly in Windows console. |
| 28 | self.spinchars = (u'-',u'\\ ',u'| ',u'/ ') |
| 29 | threading.Thread.__init__(self, None, None, "Spin Thread") |
| 30 | |
| 31 | def spin(self): |
| 32 | """ Perform a single spin """ |
| 33 | |
| 34 | for x in self.spinchars: |
| 35 | self.string = self.msg + "...\t" + x + "\r" |
| 36 | self.out.write(self.string.encode('utf-8')) |
| 37 | self.out.flush() |
| 38 | time.sleep(self.waittime) |
| 39 | |
| 40 | def run(self): |
| 41 | |
| 42 | while (not self.flag) and ((self.count<self.min) or (self.count<self.max)): |
| 43 | self.spin() |
| 44 | self.count += 1 |
| 45 | |
| 46 | # Clean up display... |
| 47 | self.out.write(" "*(len(self.string) + 1)) |
| 48 | |
| 49 | def stop(self): |
| 50 | self.flag = True |
| 51 | |
| 52 | if __name__ == "__main__": |
| 53 | spin = SpinCursor(msg="Spinning...",minspin=5,speed=5) |