3

以下のコードでは、candump という関数を開くスレッドを作成しています。Candump は入力チャネルを監視し、データが入ってくると値を std out に返します。

私がやりたいことは、これがいつ終了するか (つまり、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
4

2 に答える 2

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:タイムアウト時にサブプロセスを強制終了または終了

于 2013-03-05T00:22:36.780 に答える
0

スレッドを終了する最良の方法ではないかもしれませんが、この回答はスレッドを強制終了する方法を提供します。コードの重要なセクションでスレッドを強制終了できないようにする方法も実装する必要がある場合があることに注意してください。

于 2013-03-05T01:40:19.407 に答える