2013-03-05 3 views
3

아래 코드에서는 candump라는 함수를 여는 스레드를 만듭니다. 캔덤 ンプ은 입력 채널을 모니터링하고 데이터가 들어올 때 표준 출력 값을 반환합니다.파이썬 스레드를 종료하는 가장 좋은 방법은 무엇입니까?

내가 원하는 것은이 종료 시간 (즉, 캔슬 한 후 일정 시간)을 제어하는 ​​것입니다. 설명서를 살펴본 후 조인이 올바른 방법 일 수 있다고 생각하십니까?

잘 모르겠습니다. 이견있는 사람? 에서 인용

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)의 dup입니다. -in-python). 후자라면, 그렇지 않습니다. (_process_를 종료 할 수 있으므로 쉽게 처리 할 수 ​​있습니다.) – abarnert

답변

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 스레드를 죽일 수있는 방법을 제공합니다. 또한 코드의 중요한 부분에서 스레드가 unkillable이 될 수있는 방법을 구현해야 할 수도 있습니다.

관련 문제