Created
March 9, 2021 08:19
-
-
Save linw1995/c4a3971ac0dd8c0db6f184f401ec8c3d to your computer and use it in GitHub Desktop.
gracefully shutdown the top asyncio coroutine in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import asyncio | |
| import signal | |
| import logging | |
| import contextlib | |
| logger = logging.getLogger(__name__) | |
| def asyncio_run(coro): | |
| task = asyncio.ensure_future(coro) | |
| loop = asyncio.get_event_loop() | |
| def canceller_maker(reason): | |
| def canceller(): | |
| logger.info(reason) | |
| task.cancel() | |
| return canceller | |
| loop.add_signal_handler( | |
| sig=signal.SIGTERM, callback=canceller_maker("cancelled by user via SIGTERM") | |
| ) | |
| loop.add_signal_handler( | |
| sig=signal.SIGINT, callback=canceller_maker("cancelled by user via SIGINT") | |
| ) | |
| try: | |
| with contextlib.suppress(asyncio.CancelledError): | |
| return loop.run_until_complete(task) | |
| finally: | |
| loop.close() | |
| async def top(): | |
| try: | |
| await asyncio.sleep(10000) | |
| except asyncio.CancelledError: | |
| print("cancelled") | |
| raise | |
| asyncio_run(top()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment