如何最好地终止python线程?

问题描述:

在下面的代码中,我创建了一个打开一个名为“candump”的函数的线程。 Candump监视一个输入通道,并在数据进入时将值返回到标准输出。如何最好地终止python线程?

我想要做的是控制何时终止(即cansend后的固定时间量)。看完文档后,似乎join可能是正确的路要走?

我不确定。有什么想法吗?

import threading 
from subprocess import call, Popen,PIPE 
import time 

delay=1 

class ThreadClass(threading.Thread): 
    def run(self): 
    start=time.time() 
    proc=Popen(["candump","can0"],stdout=PIPE) 
    while True: 
     line=proc.stdout.readline() 
     if line !='': 
      print line 

t = ThreadClass() 
t.start() 
time.sleep(.1) 
call(["cansend", "can0", "-i", "0x601", "0x40", "0xF6", "0x60", "0x01", "0x00", "0x00", "0x00", "0x00"]) 
time.sleep(0.01) 
#right here is where I want to kill the ThreadClass thread 
+1

这里有一个[XY问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。你在问如何终止一个线程,或者你问如何在一个子进程中放置一个超时,并且你认为线程终止是实现它的方法?如果前者,这是一个重复[有没有什么办法杀死Python中的线程?](http://*.com/questions/323972/is-there-any-way-to-kill-a-thread -in-蟒)。如果是后者,那不是。 (你可以终止一个_process_,这很容易。) – abarnert 2013-03-05 00:26:16

import subprocess as sub 
import threading 

class RunCmd(threading.Thread): 
    def __init__(self, cmd, timeout): 
     threading.Thread.__init__(self) 
     self.cmd = cmd 
     self.timeout = timeout 

    def run(self): 
     self.p = sub.Popen(self.cmd) 
     self.p.wait() 

    def Run(self): 
     self.start() 
     self.join(self.timeout) 

     if self.is_alive(): 
      self.p.terminate() 
      self.join() 

RunCmd(["./someProg", "arg1"], 60).Run() 

引自:Python: kill or terminate subprocess when timeout

它可能不是终止线程的最佳方式,但this answer提供了一种方法来杀死一个线程。请注意,您可能还需要实现一种方法,让线程在代码的关键部分处于不可驱动状态。