from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor """ 在使用線程池/進程池之后,如果任務函數中出現異常,如果不調用result異常並不會拋出,導致一種沒有報錯的假象 """ def func(): lst = [1, 2] # 寫一個bug,測試是否或報錯 print(lst[3]) def callbak(f): exception = f.exception() if exception: # 如果exception獲取到了值,說明有異常.exception就是異常類 print(exception) if __name__ == '__main__': pool = ThreadPoolExecutor(1) # 用這種方法不會異常,ThreadPoolExecutor/ProcessPoolExecutor會將異常封裝到futures對象中,需要調用.exception()方法獲取異常 pool.submit(func).add_done_callback(callbak) pool.shutdown()