Coverage for Lib/asyncio/runners.py: 97%
119 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 05:46 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 05:46 +0000
1__all__ = ('Runner', 'run')
3import contextvars
4import enum
5import functools
6import inspect
7import threading
8import signal
9from . import coroutines
10from . import events
11from . import exceptions
12from . import tasks
13from . import constants
15class _State(enum.Enum):
16 CREATED = "created"
17 INITIALIZED = "initialized"
18 CLOSED = "closed"
21class Runner:
22 """A context manager that controls event loop life cycle.
24 The context manager always creates a new event loop,
25 allows to run async functions inside it,
26 and properly finalizes the loop at the context manager exit.
28 If debug is True, the event loop will be run in debug mode.
29 If loop_factory is passed, it is used for new event loop creation.
30 If eager_tasks is True, the loop creates eager tasks by default.
32 asyncio.run(main(), debug=True)
34 is a shortcut for
36 with asyncio.Runner(debug=True) as runner:
37 runner.run(main())
39 The run() method can be called multiple times within the runner's
40 context.
42 This can be useful for interactive console (e.g. IPython),
43 unittest runners, console tools, -- everywhere when async code
44 is called from existing sync framework and where the preferred single
45 asyncio.run() call doesn't work.
47 """
49 # Note: the class is final, it is not intended for inheritance.
51 def __init__(self, *, debug=None, loop_factory=None, eager_tasks=False):
52 self._state = _State.CREATED
53 self._debug = debug
54 self._loop_factory = loop_factory
55 self._eager_tasks = eager_tasks
56 self._loop = None
57 self._context = None
58 self._interrupt_count = 0
59 self._set_event_loop = False
61 def __enter__(self):
62 self._lazy_init()
63 return self
65 def __exit__(self, exc_type, exc_val, exc_tb):
66 self.close()
68 def close(self):
69 """Shutdown and close event loop."""
70 if self._state is not _State.INITIALIZED:
71 return
72 try:
73 loop = self._loop
74 _cancel_all_tasks(loop)
75 loop.run_until_complete(loop.shutdown_asyncgens())
76 loop.run_until_complete(
77 loop.shutdown_default_executor(constants.THREAD_JOIN_TIMEOUT))
78 finally:
79 if self._set_event_loop:
80 events.set_event_loop(None)
81 loop.close()
82 self._loop = None
83 self._state = _State.CLOSED
85 def get_loop(self):
86 """Return embedded event loop."""
87 self._lazy_init()
88 return self._loop
90 def run(self, coro, *, context=None):
91 """Run code in the embedded event loop."""
92 if events._get_running_loop() is not None:
93 # fail fast with short traceback
94 raise RuntimeError(
95 "Runner.run() cannot be called from a running event loop")
97 self._lazy_init()
99 if not coroutines.iscoroutine(coro):
100 if inspect.isawaitable(coro):
101 async def _wrap_awaitable(awaitable):
102 return await awaitable
104 coro = _wrap_awaitable(coro)
105 else:
106 raise TypeError('An asyncio.Future, a coroutine or an '
107 'awaitable is required')
109 if context is None:
110 context = self._context
112 task = self._loop.create_task(coro, context=context)
114 if (threading.current_thread() is threading.main_thread()
115 and signal.getsignal(signal.SIGINT) is signal.default_int_handler
116 ):
117 sigint_handler = functools.partial(self._on_sigint, main_task=task)
118 try:
119 signal.signal(signal.SIGINT, sigint_handler)
120 except ValueError:
121 # `signal.signal` may throw if `threading.main_thread` does
122 # not support signals (e.g. embedded interpreter with signals
123 # not registered - see gh-91880)
124 sigint_handler = None
125 else:
126 sigint_handler = None
128 self._interrupt_count = 0
129 try:
130 return self._loop.run_until_complete(task)
131 except exceptions.CancelledError:
132 if self._interrupt_count > 0: 132 ↛ 136line 132 didn't jump to line 136 because the condition on line 132 was always true
133 uncancel = getattr(task, "uncancel", None)
134 if uncancel is not None and uncancel() == 0:
135 raise KeyboardInterrupt()
136 raise # CancelledError
137 finally:
138 if (sigint_handler is not None
139 and signal.getsignal(signal.SIGINT) is sigint_handler
140 ):
141 signal.signal(signal.SIGINT, signal.default_int_handler)
143 def _lazy_init(self):
144 if self._state is _State.CLOSED:
145 raise RuntimeError("Runner is closed")
146 if self._state is _State.INITIALIZED:
147 return
148 if self._loop_factory is None:
149 self._loop = events.new_event_loop()
150 if not self._set_event_loop: 150 ↛ 157line 150 didn't jump to line 157 because the condition on line 150 was always true
151 # Call set_event_loop only once to avoid calling
152 # attach_loop multiple times on child watchers
153 events.set_event_loop(self._loop)
154 self._set_event_loop = True
155 else:
156 self._loop = self._loop_factory()
157 if self._debug is not None:
158 self._loop.set_debug(self._debug)
159 if self._eager_tasks:
160 self._loop.set_task_factory(tasks.eager_task_factory)
161 self._context = contextvars.copy_context()
162 self._state = _State.INITIALIZED
164 def _on_sigint(self, signum, frame, main_task):
165 self._interrupt_count += 1
166 if self._interrupt_count == 1 and not main_task.done(): 166 ↛ 171line 166 didn't jump to line 171 because the condition on line 166 was always true
167 main_task.cancel()
168 # wakeup loop if it is blocked by select() with long timeout
169 self._loop.call_soon_threadsafe(lambda: None)
170 return
171 raise KeyboardInterrupt()
174def run(main, *, debug=None, loop_factory=None, eager_tasks=False):
175 """Execute the coroutine and return the result.
177 This function runs the passed coroutine, taking care of
178 managing the asyncio event loop, finalizing asynchronous
179 generators and closing the default executor.
181 This function cannot be called when another asyncio event loop is
182 running in the same thread.
184 If debug is True, the event loop will be run in debug mode.
185 If loop_factory is passed, it is used for new event loop creation.
186 If eager_tasks is True, the loop creates eager tasks by default.
188 This function always creates a new event loop and closes it at the end.
189 It should be used as a main entry point for asyncio programs, and should
190 ideally only be called once.
192 The executor is given a timeout duration of 5 minutes to shutdown.
193 If the executor hasn't finished within that duration, a warning is
194 emitted and the executor is closed.
196 Example:
198 async def main():
199 await asyncio.sleep(1)
200 print('hello')
202 asyncio.run(main())
203 """
204 if events._get_running_loop() is not None:
205 # fail fast with short traceback
206 raise RuntimeError(
207 "asyncio.run() cannot be called from a running event loop")
209 with Runner(debug=debug, loop_factory=loop_factory,
210 eager_tasks=eager_tasks) as runner:
211 return runner.run(main)
214def _cancel_all_tasks(loop):
215 to_cancel = tasks.all_tasks(loop)
216 if not to_cancel:
217 return
219 for task in to_cancel:
220 task.cancel()
222 loop.run_until_complete(tasks.gather(*to_cancel, return_exceptions=True))
224 for task in to_cancel:
225 if task.cancelled():
226 continue
227 if task.exception() is not None: 227 ↛ 224line 227 didn't jump to line 224 because the condition on line 227 was always true
228 loop.call_exception_handler({
229 'message': 'unhandled exception during asyncio.run() shutdown',
230 'exception': task.exception(),
231 'task': task,
232 })