首页 > 解决方案 > 如何在 Python 中使子进程超时

问题描述

我有一个简单的 Python 线程示例,如下所示:

class MyClass(object):
    threads = 5
    def run_in_threads(self, variable1_list, variable2):
        with concurrent.futures.ThreadPoolExecutor(max_workers=threads) as executor:
            pool = {executor.submit(self.run, variable1, variable2) for variable1 in variable1_list}
            concurrent.futures.wait(pool)

    def run(self, variable1, variable2):
        t = SingleThread(scf_file_path, variable2)
        t.start()
        t.join()

class SingleThread(threading.Thread):
    def __init__(self, variable1, variable2):
        logger.debug("Single thread init.")
        threading.Thread.__init__(self)
        self.my_variable = my_variable

    def run(self):
        logger.debug("Single thread started.")
        # command = my long methond, e.g. subprocess
        p = subprocess.Popen(command)
        p.wait()
        logger.debug("Single thread ended.")

问题是有时子进程命令被卡住,然后整个进程停止(脚本的下一部分无法运行)。

您能否验证这段代码并给出提示,如果时间达到限制,例如 1 分钟,如何继续强制杀死线程?

标签: pythonmultithreadingpython-multithreading

解决方案


谢谢,@shmee 的提示。向 subprocess.wait 方法添加超时是最简单的解决方案:

def run(self):
    logger.debug("Single thread started.")
    # command = my long methond, e.g. subprocess
    p = subprocess.Popen(command)
    p.wait(timeout=60)  # <===
    logger.debug("Single thread ended.")

推荐阅读