目录解决方法1:解决方法2:pythonThreadPoolExecutor线程池的工作线程中出现异常时,主线程不会捕获异常。解决方法1:直接在需要执行的任务方法中添加try:executor=...
目录
解决方法1:解决方法2:
python ThreadPoolExecutor线程池的工作线程中出现异常时,主线程不会捕获异常。
解决方法1:
直接在需要执行的任务方法中添加try:
executor = ThreadPoolExecutor()
executor.submit(test_work, 0)
def test_work(p):
try:
1/p
except Exception as e:
logger.exception(e)
解决方法2:
添加完成运行时的callback:
executor = ThreadPoolExecutor() task = executor.submit(test_work, 0) task.add_done_callback(handle_exception)
handle_exception中又可以通过两种方式捕获异常:
2.1 通过concxPDipurrent.futures.Future.exception(timeout=None)
def handle_exception(worker):
# Method 1: concurrent.futures.Future.exception(timeout=None)
worker_exception = worker.exception()
if worker_exception:
logger.exception(worker_exception)
2.2 通过concurrent.futures.Future.result(Timeout = None)
def handle_exception(worker):
Method 2: try
try:
worker.result()
except Exception as e:
logger.exception(e)
到此这篇关于详解python ThreadPoolExecutor异常捕获的文章就介绍到这了,更多相关python ThreadPoolExecutor异常捕获内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!










