在 python 中运行线程一段时间



我有一个线程最多应该执行 3 分钟。 如果超过 3 分钟,我需要杀死它。下面给出了我当前的代码片段。请注意,我不能在 python 中使用多处理模块。

def test_th():
        p = threading.Thread(target=update_fm,name="update_fm", args=(url,))
        p.start()
        p.join(180)
        log.debug("isalive :",p.isAlive()) 
def update_fm(fv_path):
    output = None
    try:
        output = subprocess.check_output('wget {0} -O /tmp/test_fm'.format(fv_path), stderr=subprocess.STDOUT, shell=True)
    except:
        log.error("Error while downloading package, please try again")
        return FAIL
    if output:
        log.info('going to upgrade cool :)')
        return SUCCESS
    return FAIL

由于线程正在运行命令,因此您无法轻松停止它(有没有办法在 Python 中杀死线程?

但是,您可以通过终止正在执行的进程来帮助线程正常退出(并退出(:

  • check_output替换为Popen
  • 获取Popen的句柄并确保它是全球性的
  • 3 分钟后,杀死手柄:线程退出

让我们用一个独立的例子来简化它(windows,用其他平台上的其他一些阻塞内容替换notepad(:

import threading,subprocess
handle = None
def update_fm():
    global handle
    output = None
    handle = subprocess.Popen('notepad',stdout=subprocess.PIPE)
    output = handle.stdout.read()
    rc = handle.wait()   # at this point, if process is killed, the thread exits with
    print(rc)
def test_th():
        p = threading.Thread(target=update_fm)
        p.start()
        p.join(10)
        if handle:
            handle.terminate()
test_th()

在这里,如果在超时之前关闭记事本窗口,则返回代码 0,如果等待 10 秒,进程被终止,则返回代码 1。

错误处理的困难在于区分"进程已终止"和"应用程序错误"。您可以在进程被终止时设置另一个标志以产生影响。