python类中的简单线程管理

2024-05-23 13:50:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图为Python编写一个模块,它为我的程序打印文本,并在后台执行某些操作时显示一个进度条。我目前正在使用'线程'模块,但如果有其他东西可以使它更容易接受建议。在

我想知道的是两个方面,我应该如何优雅地调用这个类,以及如何停止正在创建的线程?

这是我目前正在做的:

tmp1 = textprint("hello this is text")
tmp1.start()
# do something
tmp1.stop()

到目前为止,我考虑了以下几种选择:

  • 使用线程名称找到线程的名称或拥有线程 返回一个名字然后杀死。或者传递一个类似的数字 之后进行螺纹标识。(有点麻烦,不是我的 最喜欢的解决方案。)

    发送线程.事件? -从阅读文档中我看到一个事件可以 被送去,也许可以用来阻止它?在

    或者一个with语句,但是我不清楚如何在这个上下文中使用它,而且我发现大多数python文档都非常混乱,根本不是为我编写的。

我想做的是:

echo('hello')(打印进度条等) -然后当我想停止它时echo.stop()

但问题是stop函数不知道它要停止哪个线程。在

下面是我要做的事情的一个框架:

^{pr2}$

然后这样称呼它:

echo('this is text') 

我想我也不得不这么做

import echo from print_text 

WITH的方式建议输入__enter__和{}位。我试过了,但没用,而且,我不知道我在做什么,真的很感谢你的帮助,谢谢。在


Tags: 模块进度条text文档echo名称hellois
3条回答

如果可能有多个子线程同时运行同一个目标,并希望确保所有子线程都停止,则线程名称非常有用。这似乎是一个有用的概括,在我看来也不太麻烦,但美是在旁观者的眼中:-)。以下内容:

  • 启动子线程以打印消息并启动progressbar
  • 使用启动时给定的名称停止子线程。在

这是更简单的代码。它做你想要的吗?在

import time, threading

class print_text:

    def __init__(self):
        pass

    def progress(self):
        while not self._stop:       # Update progress bar
            print(".", sep="", end="")
            time.sleep(.5)

    def echo(self, arg="Default"):  # Print message and start progress bar
        print(arg)
        self._stop = False
        threading.Thread(target=self.progress, name="_prog_").start()

    def stop(self):
        self._stop = True
        for t in threading.enumerate():
            if t.name == "_prog_":
                t.join()

tmp1 = print_text()
tmp1.echo("hello this is text")
time.sleep(10)
tmp1.stop()
print("Done")

在Python中停止线程的最好方法是礼貌地要求它停止。向线程传递新数据的最佳方法是使用Queue模块。在

这两种方法都在the code in this post中使用,它演示了从Python线程进行的套接字通信,但在其他方面与您的问题相关。如果仔细阅读代码,您会注意到:

  1. 使用threading.Event(),这是由外部的方法调用设置的,线程会定期检查它是否被要求死。在
  2. 使用Queue.Queue()向线程传递命令和从线程接收响应。在

你很快就有了工作代码。只需要做一些小改动:

  • print_text是一个类。它应该用print_text()实例化
  • start方法返回一个print\u text的实例,您需要保存它 为了调用stopechot = print_text()
  • enter方法需要返回self而不是thing。在
  • exit方法应该设置stop或调用stop()。在
  • echo方法应返回self,以便可以与with语句一起使用。在

下面是一些工作代码,其中包括这些小的编辑:

import time
import string
import threading

class print_text(threading.Thread):

    def __init__(self, arg=None):
        super(print_text,self).__init__()
        self._stop = False
        self.arg=arg

    def run (self):
        # start thread for text
        print self.txt
        while not self._stop:
                print "rude words"

    def echo (self, txt):
        self.txt=txt
        self.start()
        return self

    def stop(self):
        self._stop = True

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

    def __enter__(self):
        print "woo"
        return self

    def __exit__(self, type, value, traceback):
        self._stop = True
        return isinstance(value, TypeError)


if __name__ == '__main__':

    t = print_text()
    t.echo('this is text')
    time.sleep(3)
    t.stop()

    with print_text().echo('this is text'):
        time.sleep(3)

    print "done"

相关问题 更多 >