Debian Codegraph @

Lib/asyncio/runners.py

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