How to catch exceptions in a python run_in_executor method call
first of all, if you call time.sleep
you'll never end up running the asyncio
event loop so no results will get detected. instead of calling time.sleep
in do_it
you're better off doing something like
asyncio.get_event_loop().run_until_complete(asyncio.sleep(0.1))
Now, the return from run_in_executor is a future. If you don't mind writing an async def and using create_task
on your asyncio
loop you could do something like
async def run_long_thing(thing, *args): try: await asyncio.get_event_loop().run_in_executor(None, thing, *args) except: #do stuff
But more in line with your current code you can attach an exception callback
def callback(future):if future.exception(): #your long thing had an exception # do something with future.exception()
then when you call run_in_executor:
future = asyncio.get_event_loop().run_in_executor(None, fun, *args)future.add_done_callback(callback)
Then callback
will be called whenever your executor task completes. future.result()
will contain the result if it is no an exception, and future.exception()
will give you back any raised exception