Skip to content

Instantly share code, notes, and snippets.

@linw1995
Created March 9, 2021 08:19
Show Gist options
  • Select an option

  • Save linw1995/c4a3971ac0dd8c0db6f184f401ec8c3d to your computer and use it in GitHub Desktop.

Select an option

Save linw1995/c4a3971ac0dd8c0db6f184f401ec8c3d to your computer and use it in GitHub Desktop.
gracefully shutdown the top asyncio coroutine in Python
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