|
| 1 | +import asyncio |
| 2 | +import functools |
| 3 | +import inspect |
| 4 | +import signal |
| 5 | +import threading |
| 6 | + |
| 7 | +class Runner: |
| 8 | + """Runner is a class similar to asyncio.Runner but that we use for backward |
| 9 | + compatibility with Python 3.10 and earlier. |
| 10 | + """ |
| 11 | + |
| 12 | + def __init__(self): |
| 13 | + self._loop = asyncio.new_event_loop() |
| 14 | + self._interrupt_count = 0 |
| 15 | + |
| 16 | + def __enter__(self): |
| 17 | + return self |
| 18 | + |
| 19 | + def __exit__(self, *args, **kwargs): |
| 20 | + self.close() |
| 21 | + |
| 22 | + def close(self): |
| 23 | + try: |
| 24 | + loop = self._loop |
| 25 | + _cancel_all_tasks(loop) |
| 26 | + loop.run_until_complete(loop.shutdown_asyncgens()) |
| 27 | + if hasattr(loop, 'shutdown_default_executor'): # Python 3.9+ |
| 28 | + loop.run_until_complete(loop.shutdown_default_executor()) |
| 29 | + finally: |
| 30 | + loop.close() |
| 31 | + |
| 32 | + def get_loop(self): |
| 33 | + return self._loop |
| 34 | + |
| 35 | + def run(self, coro): |
| 36 | + if not inspect.iscoroutine(coro): |
| 37 | + raise ValueError("a coroutine was expected, got {!r}".format(coro)) |
| 38 | + |
| 39 | + try: |
| 40 | + asyncio.get_running_loop() |
| 41 | + except RuntimeError: |
| 42 | + pass |
| 43 | + else: |
| 44 | + raise RuntimeError("Runner.run() cannot be called from a running event loop") |
| 45 | + |
| 46 | + task = self._loop.create_task(coro) |
| 47 | + sigint_handler = None |
| 48 | + |
| 49 | + if (threading.current_thread() is threading.main_thread() |
| 50 | + and signal.getsignal(signal.SIGINT) is signal.default_int_handler |
| 51 | + ): |
| 52 | + sigint_handler = functools.partial(self._on_sigint, main_task=task) |
| 53 | + try: |
| 54 | + signal.signal(signal.SIGINT, sigint_handler) |
| 55 | + except ValueError: |
| 56 | + # `signal.signal` may throw if `threading.main_thread` does |
| 57 | + # not support signals (e.g. embedded interpreter with signals |
| 58 | + # not registered - see gh-91880) |
| 59 | + sigint_handler = None |
| 60 | + |
| 61 | + self._interrupt_count = 0 |
| 62 | + try: |
| 63 | + asyncio.set_event_loop(self._loop) |
| 64 | + return self._loop.run_until_complete(task) |
| 65 | + except asyncio.CancelledError: |
| 66 | + if self._interrupt_count > 0: |
| 67 | + uncancel = getattr(task, "uncancel", None) |
| 68 | + if uncancel is not None and uncancel() == 0: |
| 69 | + raise KeyboardInterrupt() |
| 70 | + raise # CancelledError |
| 71 | + finally: |
| 72 | + asyncio.set_event_loop(None) |
| 73 | + if (sigint_handler is not None |
| 74 | + and signal.getsignal(signal.SIGINT) is sigint_handler |
| 75 | + ): |
| 76 | + signal.signal(signal.SIGINT, signal.default_int_handler) |
| 77 | + |
| 78 | + def _on_sigint(self, signum, frame, main_task): |
| 79 | + self._interrupt_count += 1 |
| 80 | + if self._interrupt_count == 1 and not main_task.done(): |
| 81 | + main_task.cancel() |
| 82 | + # wakeup loop if it is blocked by select() with long timeout |
| 83 | + self._loop.call_soon_threadsafe(lambda: None) |
| 84 | + return |
| 85 | + raise KeyboardInterrupt() |
| 86 | + |
| 87 | +def _cancel_all_tasks(loop): |
| 88 | + to_cancel = asyncio.all_tasks(loop) |
| 89 | + if not to_cancel: |
| 90 | + return |
| 91 | + |
| 92 | + for task in to_cancel: |
| 93 | + task.cancel() |
| 94 | + |
| 95 | + loop.run_until_complete(asyncio.gather(*to_cancel, return_exceptions=True)) |
| 96 | + |
| 97 | + for task in to_cancel: |
| 98 | + if task.cancelled(): |
| 99 | + continue |
| 100 | + if task.exception() is not None: |
| 101 | + loop.call_exception_handler({ |
| 102 | + 'message': 'unhandled exception during asyncio.run() shutdown', |
| 103 | + 'exception': task.exception(), |
| 104 | + 'task': task, |
| 105 | + }) |
0 commit comments