如何在Python中停止线程中的for循环? [英] How to stop a for loop in a thread in Python?

查看:0
本文介绍了如何在Python中停止线程中的for循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用Python语言创建一个脚本来学习线程化,但我似乎无法停止线程中的for循环。目前,我正在使用pyInstaller编译脚本并结束线程进程,我知道这不是最好的方法,有人能解释一下如何根据命令结束线程吗?我读过很多其他的问题,但我似乎不明白如何以"正确"的方式停止一条线索。以下是我现在用来测试它的代码:

class Thread(Thread):
        def __init__(self, command, call_back):
        self._command = command
        self._call_back = call_back
        super(Thread, self).__init__()

    def run(self):
        self._command()
        self._call_back()
def test():
    i = 20
    for n in range(0,i):
        #This is to keep the output at a constant speed
        sleep(.5)
        print n
def thread_stop():
    procs = str(os.getpid())
    PROCNAME = 'spam.exe'
    for proc in psutil.process_iter():
        if proc.name == PROCNAME:
            text = str(proc)[19:]
            head, sep, tail = text.partition(',')
            if str(head) != procs:
                subprocess.call(['taskkill', '/PID', str(head), '/F'])

这些函数由Tkinter中制作的图形用户界面调用,目前还可以。

如果您不想阅读所有这些内容,请直截了当地说:当在Python线程中存在for循环时,如何以"正确的方式"停止线程?谢谢!

编辑:对不起,我删除了我认为最重要的代码。相反,下面是完整的代码(这是我用来学习Python的文本消息程序,但上面是我在开始理解它之前第一次尝试线程化)。http://pastebin.com/qaPux1yR

推荐答案

切勿强行终止线程。取而代之的是使用线程定期检查的某种"信号",如果进行了设置,则线程会很好地完成。

最简单的"Signal"是一个简单的布尔变量,可以使用如下形式:

class MyThread(Thread):
    def __init__(self):
        self.continue = True

    def run(self):
        while (self.continue):
            # Do usefull stuff here
            pass

    def stop(self):
        self.continue = False

这篇关于如何在Python中停止线程中的for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆