Debian Codegraph @

Doc/library/asyncio-runner.rst

raw
1 .. currentmodule:: asyncio
2
3
4 =======
5 Runners
6 =======
7
8 **Source code:** :source:`Lib/asyncio/runners.py`
9
10
11 This section outlines high-level asyncio primitives to run asyncio code.
12
13 They are built on top of an :ref:`event loop <asyncio-event-loop>` with the aim
14 to simplify async code usage for common wide-spread scenarios.
15
16 .. contents::
17 :depth: 1
18 :local:
19
20
21
22 Running an asyncio Program
23 ==========================
24
25 .. function:: run(coro, *, debug=None, loop_factory=None)
26
27 Execute *coro* in an asyncio event loop and return the result.
28
29 The argument can be any awaitable object.
30
31 This function runs the awaitable, taking care of managing the
32 asyncio event loop, *finalizing asynchronous generators*, and
33 closing the executor.
34
35 This function cannot be called when another asyncio event loop is
36 running in the same thread.
37
38 If *debug* is ``True``, the event loop will be run in debug mode. ``False`` disables
39 debug mode explicitly. ``None`` is used to respect the global
40 :ref:`asyncio-debug-mode` settings.
41
42 If *loop_factory* is not ``None``, it is used to create a new event loop;
43 otherwise :func:`asyncio.new_event_loop` is used. The loop is closed at the end.
44 This function should be used as a main entry point for asyncio programs,
45 and should ideally only be called once. It is recommended to use
46 *loop_factory* to configure the event loop instead of policies.
47 Passing :class:`asyncio.EventLoop` allows running asyncio without the
48 policy system.
49
50 The executor is given a timeout duration of 5 minutes to shutdown.
51 If the executor hasn't finished within that duration, a warning is
52 emitted and the executor is closed.
53
54 Example::
55
56 async def main():
57 await asyncio.sleep(1)
58 print('hello')
59
60 asyncio.run(main())
61
62 .. versionadded:: 3.7
63
64 .. versionchanged:: 3.9
65 Updated to use :meth:`loop.shutdown_default_executor`.
66
67 .. versionchanged:: 3.10
68
69 *debug* is ``None`` by default to respect the global debug mode settings.
70
71 .. versionchanged:: 3.12
72
73 Added *loop_factory* parameter.
74
75 .. versionchanged:: 3.14
76
77 *coro* can be any awaitable object.
78
79 .. note::
80
81 The :mod:`!asyncio` policy system is deprecated and will be removed
82 in Python 3.16; from there on, an explicit *loop_factory* is needed
83 to configure the event loop.
84
85
86 Runner context manager
87 ======================
88
89 .. class:: Runner(*, debug=None, loop_factory=None)
90
91 A context manager that simplifies *multiple* async function calls in the same
92 context.
93
94 Sometimes several top-level async functions should be called in the same :ref:`event
95 loop <asyncio-event-loop>` and :class:`contextvars.Context`.
96
97 If *debug* is ``True``, the event loop will be run in debug mode. ``False`` disables
98 debug mode explicitly. ``None`` is used to respect the global
99 :ref:`asyncio-debug-mode` settings.
100
101 *loop_factory* could be used for overriding the loop creation.
102 It is the responsibility of the *loop_factory* to set the created loop as the
103 current one. By default :func:`asyncio.new_event_loop` is used and set as
104 current event loop with :func:`asyncio.set_event_loop` if *loop_factory* is ``None``.
105
106 Basically, :func:`asyncio.run` example can be rewritten with the runner usage::
107
108 async def main():
109 await asyncio.sleep(1)
110 print('hello')
111
112 with asyncio.Runner() as runner:
113 runner.run(main())
114
115 .. versionadded:: 3.11
116
117 .. method:: run(coro, *, context=None)
118
119 Execute *coro* in the embedded event loop.
120
121 The argument can be any awaitable object.
122
123 If the argument is a coroutine, it is wrapped in a Task.
124
125 An optional keyword-only *context* argument allows specifying a
126 custom :class:`contextvars.Context` for the code to run in.
127 The runner's default context is used if context is ``None``.
128
129 Returns the awaitable's result or raises an exception.
130
131 This function cannot be called when another asyncio event loop is
132 running in the same thread.
133
134 .. versionchanged:: 3.14
135
136 *coro* can be any awaitable object.
137
138 .. method:: close()
139
140 Close the runner.
141
142 Finalize asynchronous generators, shutdown default executor, close the event loop
143 and release embedded :class:`contextvars.Context`.
144
145 .. method:: get_loop()
146
147 Return the event loop associated with the runner instance.
148
149 .. note::
150
151 :class:`Runner` uses the lazy initialization strategy, its constructor doesn't
152 initialize underlying low-level structures.
153
154 Embedded *loop* and *context* are created at the :keyword:`with` body entering
155 or the first call of :meth:`run` or :meth:`get_loop`.
156
157
158 Handling Keyboard Interruption
159 ==============================
160
161 .. versionadded:: 3.11
162
163 When :const:`signal.SIGINT` is raised by :kbd:`Ctrl-C`, :exc:`KeyboardInterrupt`
164 exception is raised in the main thread by default. However this doesn't work with
165 :mod:`asyncio` because it can interrupt asyncio internals and can hang the program from
166 exiting.
167
168 To mitigate this issue, :mod:`asyncio` handles :const:`signal.SIGINT` as follows:
169
170 1. :meth:`asyncio.Runner.run` installs a custom :const:`signal.SIGINT` handler before
171 any user code is executed and removes it when exiting from the function.
172 2. The :class:`~asyncio.Runner` creates the main task for the passed coroutine for its
173 execution.
174 3. When :const:`signal.SIGINT` is raised by :kbd:`Ctrl-C`, the custom signal handler
175 cancels the main task by calling :meth:`asyncio.Task.cancel` which raises
176 :exc:`asyncio.CancelledError` inside the main task. This causes the Python stack
177 to unwind, ``try/except`` and ``try/finally`` blocks can be used for resource
178 cleanup. After the main task is cancelled, :meth:`asyncio.Runner.run` raises
179 :exc:`KeyboardInterrupt`.
180 4. A user could write a tight loop which cannot be interrupted by
181 :meth:`asyncio.Task.cancel`, in which case the second following :kbd:`Ctrl-C`
182 immediately raises the :exc:`KeyboardInterrupt` without cancelling the main task.