我正在尝试用 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 中的 GUI 调用,目前还可以。
如果您不想阅读所有内容,请直接关注:当 Python 线程中存在 for 循环时,如何以“正确的方式”停止线程?谢谢!
编辑:抱歉,我提取了我认为最重要的代码。相反,这里是完整的代码(它是一个文本消息发送器,我用它来学习 Python,但是上面是我在开始理解它之前第一次尝试线程)。http://pastebin.com/qaPux1yR 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)