2013-03-05 109 views
3

在下面的代碼中,我創建了一個打開一個名爲「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://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread -in-蟒)。如果是後者,那不是。 (你可以終止一個_process_,這很容易。) – abarnert 2013-03-05 00:26:16

回答

1
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

0

它可能不是終止線程的最佳方式,但this answer提供了一種方法來殺死一個線程。請注意,您可能還需要實現一種方法,讓線程在代碼的關鍵部分處於不可驅動狀態。