-1

Considering the following code:

import asyncio


async def main() -> None:
    await asyncio.sleep(2**256)


if __name__ == '__main__':
    asyncio.run(main())

What is the most proper way to terminate coroutine main, after it has been called by asyncio.run? When I invoked script and pressed CTRL + C, I saw an ugly traceback.

As I can see from the source code, asyncio.run does a lot of machinery behind the scenes, so I would like to continue using it.

1 Answers1

-1

You probably should handle the SIGINT signal.

import asyncio
import functools
import signal

async def main() -> None:
    await asyncio.sleep(2**256)

def handler(loop):
    ...


if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.add_signal_handler(signal.SIGINT, functools.partial(handler, loop=loop))
    loop.run_until_complete(main())

The question is how the handler should look like? If you want just close program without exception, use sys.exit()

def handler(loop):
    sys.exit()

However to close everything gracefully, you need to finish every task and stop the loop. See this topic for more insight.

kosciej16
  • 6,294
  • 1
  • 18
  • 29