在类中实现旋转器类型对象作为子进程

2 投票
1 回答
714 浏览
提问于 2025-04-17 07:20

我刚开始学习编程,今天才开始接触类的概念。我想做一个类似“旋转器”的对象,想要像这样调用它:我有点困惑的是应该使用“线程”、“线程库”还是“进程”。我看到有地方说一个线程的实例占用8MB的内存,但因为我做的只是一个简单的文本旋转器,所以不想用太多内存。我的第一个问题是应该用哪个模块,第二个问题是如何在一个类中实现它,这样我就可以像这样调用:

spin.start() - starts it

spin.stop() -  stops it

spin.cursor_invisible() - turns the cursor invisible

spin.cursor_visible() - cursor visible!

我复制了一些代码,也看了一些书,但还是有点困惑。我现在的进展是这样的:我在代码里加了一些注释,说明我有多无知。不过我确实读了很多书,真的!这真的是个很大的概念,挺难理解的。

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 个回答

2

我稍微修改了一下你的代码。现在它可以运行了!首先是带注释的版本:

第一行告诉Python这个源文件包含utf-8字符。

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

然后你需要导入所有你最终会用到的东西。你不一定要像这样把它放在文件的顶部,但我习惯这样,因为我之前是做C语言的...

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

因为你在重写线程.Thread的init方法,所以你需要调用父类的init方法,以确保对象被正确初始化。

        self._stop = False

我把这个改成了布尔值。使用线程.Event对于这个来说有点过于复杂了。

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

这里是没有注释的版本...

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

撰写回答