python - 如何在 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 分钟,如何继续强制杀死线程?
解决方案
谢谢,@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.")
推荐阅读
- vue.js - 构建web组件时如何使用vue.js组件库
- reactjs - 嵌套对象的 Axios 发布请求
- asp.net-core - 如何在 .netcore 中将 Word 转换为 Pdf
- javascript - 承诺在 Javascript 中无法以同步方式解决问题
- flutter - Flutter、pdf包和表格组件
- java - 如何检查用户何时单击了正确的按钮?
- c# - UWP 应用程序:地图路线 API (MapRouteFinder.GetDrivingRouteAsync) 不响应,甚至无法刷新或取消请求
- laravel - OOP Laravel 解析从 DB 获取的数据
- pine-script - 如何从 Pine Script (Tradingview) 中的特定日期获取绿色和红色音量条计数?
- javascript - 如何将属性直接传递给 vuejs 中的组件,例如 reactjs