日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

詳解python?ThreadPoolExecutor異常捕獲_python

作者:ldahual ? 更新時間: 2023-03-23 編程語言

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

欄目分類
最近更新