I'm a total beginner and only started doing classes today, and im trying to make a sort of 'spinner' object i can call something like this: One of the things im confused about is whether to use 'thread', 'threading' or 'processes'. I just read somewhere that an instance of a thread costs 8meg, as this is a simple text spinner thing, it doesnt warrant using a huge amount of memory. My first question is which module should I use, and my second is how do implement this in a class so i can call it like this:
spin.start() - starts it
spin.stop() - stops it
spin.cursor_invisible() - turns the cursor invisible
spin.cursor_visible() - cursor visible!
I copied some code and read some books but Im a bit confused, what I have so far is this: i put some comments in to show how ignorant I am. I have been reading a lot though, honest! Its kind of a large thing to get your head around.
spinner="▏▎▍▌▋▊▉█▉▊▌▍▎" #utf8
#convert the utf8 spinner string to a list
chars=[c.encode("utf-8") for c in unicode(spinner,"utf-8")]
class spin(): # not sure what to put in the brackets was (threading.Thread, but now im not sure whether to use processes or not)
def __init__(self):
super(spin, self).__init__() # dont understand what this does
self._stop = threading.Event()
def run (self):
threading.Thread(target = self).run()
pos=0
while not self._stop:
sys.stdout.write("\r"+chars[pos])
sys.stdout.flush()
time.sleep(.15)
pos+=1
pos%=len(chars)
def cursor_visible(self):
os.system("tput cvvis")
def cursor_invisible(self):
os.system("tput civis")
def stop(self):
self._stop.set() #the underscore makes this a private variable ?
def stopped(self):
return self._stop.isSet()
I have altered your code slightly. Now it runs! First a commented version:
The first line tells python that this source file contains utf-8 characters
Then you need to import all the stuff that you will eventually use. You dont have to do it at the top of the file like this, but I'm a C guy and this is how I like it...
Threading is fine for this
Since you are overriding the init method of threading.Thread with your own init you need to call the parent class's init to make sure the object is properly initiated.
I changed this to a boolean. The threading.Event is overkill for this.
Sort of. It's not actually private, the underscore just tells everyone that it's bad form to acces it.
And finally a small test of the code:
And here is the uncommented version...