[英]How to stop a for loop in a thread in Python?
我试图在Python中创建一个脚本来学习线程,但似乎无法停止线程中的for循环。 目前,我正在使用pyInstaller编译脚本并结束Thread进程,我知道这不是最好的方法,有人可以向我解释如何在命令中结束线程吗? 我已经阅读了许多其他问题,但是我似乎无法理解如何以“正确”的方式停止线程。 这是到目前为止我正在使用的代码进行测试:
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中的GUI调用,目前还不错。
如果您不想阅读所有内容,请直达这一点:当Python中的线程中存在for循环时,如何以“正确的方式”停止线程? 谢谢!
编辑:抱歉,我取消了我认为最重要的代码。 相反,这是完整的代码(这是我用来学习Python的文本消息器,但是以上是我开始理解之前的第一次尝试线程化)。 http://pastebin.com/qaPux1yR
您永远不应强行杀死线程。 而是使用某种线程定期检查的“信号”,如果设置了该信号,则线程会顺利完成。
最简单的“信号”类型是一个简单的布尔变量,可以像这样使用:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.