Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How best to terminate a python thread?

In the code below I am creating a thread that opens up a function called candump. Candump monitors an input channel and returns values to std out as data comes in.

What I want to do is have control over when this terminates (ie, a fixed amount of time after cansend). After looking through the documentation it seems like join might be the right way to go?

I'm not sure. Any thoughts?

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
like image 372
Chris Avatar asked Dec 13 '25 16:12

Chris


1 Answers

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()

cited from : Python: kill or terminate subprocess when timeout

like image 72
zzk Avatar answered Dec 15 '25 07:12

zzk