【问题标题】:How best to terminate a python thread?如何最好地终止 python 线程?
【发布时间】:2013-03-05 00:18:59
【问题描述】:

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

我想要做的是控制何时终止(即,在 cansend 之后的固定时间量)。查看文档后,似乎加入可能是正确的方法?

我不确定。有什么想法吗?

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 problem。您是在问如何终止线程,还是在问如何在子进程上设置超时,而您只是认为线程终止是这样做的方法?如果是前者,这是Is there any way to kill a Thread in Python? 的重复。如果是后者,那就不是。 (您可以终止一个进程,这很容易。)

标签: python subprocess


【解决方案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

【讨论】:

    【解决方案2】:

    这可能不是终止线程的最佳方法,但this answer 提供了一种终止线程的方法。请注意,您可能还需要实现一种方法,使线程在其代码的关键部分无法被杀死。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-28
      • 2017-11-17
      • 1970-01-01
      • 2015-06-07
      • 2014-09-09
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多