如何最好地终止python线程?

2024-06-23 19:17:36 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,我正在创建一个线程,它打开一个名为candump的函数。Candump监视输入通道,并在数据进入时将值返回到std out。在

我想做的是控制何时终止(即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

Tags: importtimestdoutlinesleepproccallstart
2条回答
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提供了一种终止线程的方法。请注意,您可能还需要实现一种方法,使线程在其代码的关键部分不可更改。在

相关问题 更多 >

    热门问题