在下面的代碼中,我創建了一個打開一個名爲「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
這裏有一個[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