implementing a spinner type object in a class as a

2020-04-15 15:06发布

问题:

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()

回答1:

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

# -*- coding: utf-8 -*- 

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...

import threading
import sys
import time
import os

spinner="▏▎▍▌▋▊▉█▉▊▌▍▎" #utf8

#convert the utf8 spinner string to a list
chars=[c.encode("utf-8") for c in unicode(spinner,"utf-8")]

class spin(threading.Thread):   # not sure what to put in the brackets was (threading.Thread, but now im not sure whether to use processes or not)

Threading is fine for this

    def __init__(self):
        super(spin,self).__init__() # dont understand what this does

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.

        self._stop = False

I changed this to a boolean. The threading.Event is overkill for this.

    def run (self):
        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 = True  #the underscore makes this a private variable ?

Sort of. It's not actually private, the underscore just tells everyone that it's bad form to acces it.

    def stopped(self):
        return self._stop == True

And finally a small test of the code:

if __name__ == "__main__":
    s = spin()
    s.cursor_invisible()
    s.start()
    a = raw_input("")
    s.stop()
    s.cursor_visible()

And here is the uncommented version...

# -*- coding: utf-8 -*- 

import threading
import sys
import time
import os

spinner="▏▎▍▌▋▊▉█▉▊▌▍▎" #utf8

#convert the utf8 spinner string to a list
chars=[c.encode("utf-8") for c in unicode(spinner,"utf-8")]

class spin(threading.Thread):   # 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 = False

    def run (self):
        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 = True  #the underscore makes this a private variable ?
    def stopped(self):
        return self._stop == True


if __name__ == "__main__":
    s = spin()
    s.cursor_invisible()
    s.start()
    a = raw_input("")
    s.stop()
    s.cursor_visible()