如何最好地终止一个Python线程?

3 投票
2 回答
934 浏览
提问于 2025-04-17 17:56

在下面的代码中,我创建了一个线程,这个线程会打开一个叫做candump的函数。candump的作用是监控一个输入通道,并在有数据进来的时候把这些数据输出到标准输出。

我想要做的是控制这个线程什么时候结束,也就是说,在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

2 个回答

0

虽然这可能不是结束线程的最佳方法,但这个回答提供了一种终止线程的方式。要注意的是,你可能还需要在线程代码的关键部分实现一种让线程无法被终止的机制。

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:超时后如何杀死或终止子进程

撰写回答