Run a coroutine inside the embedded event loop.
(self, coro, *, context=None)
| 84 | return self._loop |
| 85 | |
| 86 | def run(self, coro, *, context=None): |
| 87 | """Run a coroutine inside the embedded event loop.""" |
| 88 | if not coroutines.iscoroutine(coro): |
| 89 | raise ValueError("a coroutine was expected, got {!r}".format(coro)) |
| 90 | |
| 91 | if events._get_running_loop() is not None: |
| 92 | # fail fast with short traceback |
| 93 | raise RuntimeError( |
| 94 | "Runner.run() cannot be called from a running event loop") |
| 95 | |
| 96 | self._lazy_init() |
| 97 | |
| 98 | if context is None: |
| 99 | context = self._context |
| 100 | task = self._loop.create_task(coro, context=context) |
| 101 | |
| 102 | if (threading.current_thread() is threading.main_thread() |
| 103 | and signal.getsignal(signal.SIGINT) is signal.default_int_handler |
| 104 | ): |
| 105 | sigint_handler = functools.partial(self._on_sigint, main_task=task) |
| 106 | try: |
| 107 | signal.signal(signal.SIGINT, sigint_handler) |
| 108 | except ValueError: |
| 109 | # `signal.signal` may throw if `threading.main_thread` does |
| 110 | # not support signals (e.g. embedded interpreter with signals |
| 111 | # not registered - see gh-91880) |
| 112 | sigint_handler = None |
| 113 | else: |
| 114 | sigint_handler = None |
| 115 | |
| 116 | self._interrupt_count = 0 |
| 117 | try: |
| 118 | return self._loop.run_until_complete(task) |
| 119 | except exceptions.CancelledError: |
| 120 | if self._interrupt_count > 0: |
| 121 | uncancel = getattr(task, "uncancel", None) |
| 122 | if uncancel is not None and uncancel() == 0: |
| 123 | raise KeyboardInterrupt() |
| 124 | raise # CancelledError |
| 125 | finally: |
| 126 | if (sigint_handler is not None |
| 127 | and signal.getsignal(signal.SIGINT) is sigint_handler |
| 128 | ): |
| 129 | signal.signal(signal.SIGINT, signal.default_int_handler) |
| 130 | |
| 131 | def _lazy_init(self): |
| 132 | if self._state is _State.CLOSED: |