How to catch exceptions in python run_in_executor method call

How can I throw an exception in the run_long_thing () function called with run_in_executor? It seems like they are swallowing it. I do not need the result of the function in the block block. This is basically a function of fire and forgetting, but still I need to catch the exceptions, if any ...

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()
+4
source share
1 answer

first of all, if you call time.sleep, you will never end the event loop asyncio, so the results will not be detected. instead of calling time.sleepin do_ityou better do something like

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

run_in_executor - . aync def create_task asyncio, -

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()

+2

Source: https://habr.com/ru/post/1687588/


All Articles