Where to catch a keyboard interrupt in asyncio: at code entry point or main function?

Viewed 204

I am working with a bluetooth bleak program using the asyncio module, and I'm trying to find a way to gracefully close the running tasks and event loop after a keyboard interrupt as well as save an array to a txt file before the program closes. I am not sure if the best place to try to catch an interrupt as at the entry point in the if __name__ == "__main__ portion of the script or in the actual main function.

The entry point and main function like the following:

async def main(ADDRESS, OUTLET):
    try:
        async with BleakClient(ADDRESS) as client:
            tasks = [
                asyncio.ensure_future(run(client, True)),
            ]

            await asyncio.gather(*tasks)
    except:
        pass


if __name__ == "__main__":
    os.environ["PYTHONASYNCIODEBUG"] = str(1)
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(main(ADDRESS, OUTLET))

From what I've seen posted in other places, some signal interrupt handlers are placed in the entry point using the try: except: finally structure, while others place them in the main function.

Without writing a custom signal handler, it seems like it should be possible to use an except clause to cancel() all tasks in loop as well as print arrays to txt before exiting, but I'm unclear as to which of these two code sections (if __name__ or main()) would be the place to put it. Any advice would be welcome. Thank you.

0 Answers
Related