Skip to content
This repository has been archived by the owner on Mar 6, 2024. It is now read-only.

Commit

Permalink
Cancel task if exception occurs in asyncio.run, fixes #58
Browse files Browse the repository at this point in the history
  • Loading branch information
erdewit committed Nov 25, 2021
1 parent b69926a commit 3956103
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions nest_asyncio.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import os
import sys
import threading
from contextlib import contextmanager
from contextlib import contextmanager, suppress
from heapq import heappop


Expand All @@ -26,10 +26,17 @@ def _patch_asyncio():
Patch asyncio module to use pure Python tasks and futures,
use module level _current_tasks, all_tasks and patch run method.
"""
def run(future, *, debug=False):
def run(coro, *, debug=False):
loop = asyncio.get_event_loop()
loop.set_debug(debug)
return loop.run_until_complete(future)
task = asyncio.ensure_future(coro)
try:
return loop.run_until_complete(task)
finally:
if not task.done():
task.cancel()
with suppress(asyncio.CancelledError):
loop.run_until_complete(task)

if sys.version_info >= (3, 6, 0):
asyncio.Task = asyncio.tasks._CTask = asyncio.tasks.Task = \
Expand Down

0 comments on commit 3956103

Please sign in to comment.