网络编程
位置:首页>> 网络编程>> Python编程>> 详解python ThreadPoolExecutor异常捕获

详解python ThreadPoolExecutor异常捕获

作者:ldahual  发布时间:2023-08-09 12:54:30 

标签:python,ThreadPoolExecutor,异常捕获

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 通过concurrent.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)

来源:https://blog.csdn.net/ldahual/article/details/128134915

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com