spinner.py

This file can be used as a module or run as a python program.

#!/usr/bin/python

import sys
import time

SpinScreenPos = 12    #Set the screen position of the spinner (chars from the left).
CharIndexPos = 0        #Set the current index position in the spinner character list.
SleepTime = .05           #Set the time between character changes in the spinner.
SpinType = 0                #Set the spinner type: 0-3
SpinCount = 500          #Set the number of times to change the spinner character.

class Spinner:
    def __init__(self, type=SpinType):
        if type == 0:
            self.char = ['O', 'o', '-', 'o','0']
        elif type == 1:
            self.char = ['.', 'o', 'O', 'o','.']
        elif type == 2:
            self.char = ['|', '/', '-', '\\', '-']
        else:
            self.char = ['*','#','@','%','+']
        self.len  = len(self.char)

    def Print(self,crnt):
        str, crnt = self.curr(crnt)
        sys.stdout.write("\b \b%s" % str)
        sys.stdout.flush() #Flush stdout to get output before sleeping!
        time.sleep(SleepTime)
        return crnt

    def curr(self,crnt): #Iterator for the character list position
        if crnt == 4:
            return self.char[4], 0
        elif crnt == 0:
            return self.char[0], 1
        else:
            test = crnt
            crnt += 1
            return self.char[test], crnt
    
    def Done(self):
        sys.stdout.write("\b \b")

if __name__ == "__main__":
    s = Spinner()
    print " " * SpinScreenPos, #the comma keeps print from ending with a newline.
    for i in range(SpinCount):
        CharIndexPos = s.Print(CharIndexPos)
    s.Done()