簡體   English   中英

如何在python run_in_executor方法調用中捕獲異常

[英]How to catch exceptions in a python run_in_executor method call

如何在run_in_executor調用的run_long_thing()函數中引發異常? 看起來它正在被吞噬。 我不需要阻塞代碼中的函數結果。 它基本上是一個火災和遺忘功能,但如果有任何問題,我仍需要捕捉異常......

import asyncio
import time


def fire_and_forget(task, *args, **kwargs):
    loop = asyncio.get_event_loop()
    if callable(task):
        #if threadpoolworker is set to None,
        #the max_workers will default to the number of processors on the machine, multiplied by 5
        return loop.run_in_executor(None, task, *args, **kwargs)
    else:    
        raise TypeError('Task must be a callable.')


async def run_long_thing(sleep):
    print("Doing long thing... {:}".format(sleep))
    time.sleep(sleep)
    print("Done doing long thing. {:}".format(sleep))
    raise Exception("sh*t happens")


def do_it():
    print("Starting my main thing...")
    print("Calling my long thing...")
    for i in range(0,10,1):
        try:
            fire_and_forget(run_long_thing, i)
            print(i)
            print("Pom pi dom...")
            time.sleep(0.1)
            print("POOOOM Pom pi dom...")
        except:
            print("can i see the sh*t?")

do_it()

首先,如果你調用time.sleep你永遠不會結束運行asyncio事件循環所以沒有結果檢測到。 而不是調用time.sleepdo_it你最好不要做這樣的事情

asyncio.get_event_loop().run_until_complete(asyncio.sleep(0.1))

現在,run_in_executor的返回是一個未來。 如果您不介意編寫異步def並在asyncio循環上使用create_task ,您可以執行類似的操作

async def run_long_thing(thing, *args):
    try: await asyncio.get_event_loop().run_in_executor(None, thing, *args)
    except:
        #do stuff

但是更符合您當前的代碼,您可以附加異常回調

def callback(future):
if future.exception(): #your long thing had an exception
        # do something with future.exception()

那么當你調用run_in_executor時:

future = asyncio.get_event_loop().run_in_executor(None, fun, *args)
future.add_done_callback(callback)

然后,只要執行程序任務完成,就會調用callback future.result()將包含結果,如果它不是一個例外, future.exception()將返回任何引發的異常

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM