blob: 240d814f13dea93e67d5d407662cc7a77eb18f14 [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +01002
Yury Selivanov7c7605f2018-09-11 09:54:40 -07003
4==========
5Event Loop
6==========
7
Kyle Stanleyf9000642019-10-10 19:18:46 -04008**Source code:** :source:`Lib/asyncio/events.py`,
9:source:`Lib/asyncio/base_events.py`
10
11------------------------------------
Yury Selivanov7c7605f2018-09-11 09:54:40 -070012
13.. rubric:: Preface
14
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040015The event loop is the core of every asyncio application.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070016Event loops run asynchronous tasks and callbacks, perform network
Carol Willing5b7cbd62018-09-12 17:05:17 -070017IO operations, and run subprocesses.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070018
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040019Application developers should typically use the high-level asyncio functions,
20such as :func:`asyncio.run`, and should rarely need to reference the loop
21object or call its methods. This section is intended mostly for authors
22of lower-level code, libraries, and frameworks, who need finer control over
23the event loop behavior.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070024
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040025.. rubric:: Obtaining the Event Loop
Yury Selivanov7c7605f2018-09-11 09:54:40 -070026
27The following low-level functions can be used to get, set, or create
28an event loop:
29
30.. function:: get_running_loop()
31
32 Return the running event loop in the current OS thread.
33
34 If there is no running event loop a :exc:`RuntimeError` is raised.
35 This function can only be called from a coroutine or a callback.
36
37 .. versionadded:: 3.7
38
39.. function:: get_event_loop()
40
41 Get the current event loop. If there is no current event loop set
42 in the current OS thread and :func:`set_event_loop` has not yet
43 been called, asyncio will create a new event loop and set it as the
44 current one.
45
Carol Willing5b7cbd62018-09-12 17:05:17 -070046 Because this function has rather complex behavior (especially
47 when custom event loop policies are in use), using the
48 :func:`get_running_loop` function is preferred to :func:`get_event_loop`
49 in coroutines and callbacks.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070050
Carol Willing5b7cbd62018-09-12 17:05:17 -070051 Consider also using the :func:`asyncio.run` function instead of using
52 lower level functions to manually create and close an event loop.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070053
54.. function:: set_event_loop(loop)
55
56 Set *loop* as a current event loop for the current OS thread.
57
58.. function:: new_event_loop()
59
60 Create a new event loop object.
61
62Note that the behaviour of :func:`get_event_loop`, :func:`set_event_loop`,
63and :func:`new_event_loop` functions can be altered by
64:ref:`setting a custom event loop policy <asyncio-policies>`.
65
66
67.. rubric:: Contents
68
69This documentation page contains the following sections:
70
Carol Willing5b7cbd62018-09-12 17:05:17 -070071* The `Event Loop Methods`_ section is the reference documentation of
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040072 the event loop APIs;
Yury Selivanov7c7605f2018-09-11 09:54:40 -070073
74* The `Callback Handles`_ section documents the :class:`Handle` and
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040075 :class:`TimerHandle` instances which are returned from scheduling
76 methods such as :meth:`loop.call_soon` and :meth:`loop.call_later`;
Yury Selivanov7c7605f2018-09-11 09:54:40 -070077
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040078* The `Server Objects`_ section documents types returned from
Yury Selivanov7c7605f2018-09-11 09:54:40 -070079 event loop methods like :meth:`loop.create_server`;
80
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040081* The `Event Loop Implementations`_ section documents the
Yury Selivanov7c7605f2018-09-11 09:54:40 -070082 :class:`SelectorEventLoop` and :class:`ProactorEventLoop` classes;
83
84* The `Examples`_ section showcases how to work with some event
85 loop APIs.
86
87
Victor Stinner9592edb2014-02-02 15:03:02 +010088.. _asyncio-event-loop:
Victor Stinnerea3183f2013-12-03 01:08:00 +010089
Yury Selivanov7c7605f2018-09-11 09:54:40 -070090Event Loop Methods
91==================
Victor Stinnerea3183f2013-12-03 01:08:00 +010092
Carol Willing5b7cbd62018-09-12 17:05:17 -070093Event loops have **low-level** APIs for the following:
lf627d2c82017-07-25 17:03:51 -060094
Yury Selivanov7c7605f2018-09-11 09:54:40 -070095.. contents::
96 :depth: 1
97 :local:
Victor Stinnerea3183f2013-12-03 01:08:00 +010098
Victor Stinnerea3183f2013-12-03 01:08:00 +010099
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700100Running and stopping the loop
101^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100102
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700103.. method:: loop.run_until_complete(future)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100104
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400105 Run until the *future* (an instance of :class:`Future`) has
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700106 completed.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100107
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700108 If the argument is a :ref:`coroutine object <coroutine>` it
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400109 is implicitly scheduled to run as a :class:`asyncio.Task`.
Eli Bendersky136fea22014-02-09 06:55:58 -0800110
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700111 Return the Future's result or raise its exception.
Guido van Rossumf68afd82016-08-08 09:41:21 -0700112
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700113.. method:: loop.run_forever()
Guido van Rossumf68afd82016-08-08 09:41:21 -0700114
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700115 Run the event loop until :meth:`stop` is called.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100116
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700117 If :meth:`stop` is called before :meth:`run_forever()` is called,
118 the loop will poll the I/O selector once with a timeout of zero,
119 run all callbacks scheduled in response to I/O events (and
120 those that were already scheduled), and then exit.
Victor Stinner83704962015-02-25 14:24:15 +0100121
Guido van Rossum41f69f42015-11-19 13:28:47 -0800122 If :meth:`stop` is called while :meth:`run_forever` is running,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700123 the loop will run the current batch of callbacks and then exit.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400124 Note that new callbacks scheduled by callbacks will not run in this
Carol Willing5b7cbd62018-09-12 17:05:17 -0700125 case; instead, they will run the next time :meth:`run_forever` or
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700126 :meth:`run_until_complete` is called.
Guido van Rossum41f69f42015-11-19 13:28:47 -0800127
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700128.. method:: loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100129
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700130 Stop the event loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100131
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700132.. method:: loop.is_running()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100133
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700134 Return ``True`` if the event loop is currently running.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100135
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700136.. method:: loop.is_closed()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100137
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700138 Return ``True`` if the event loop was closed.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100139
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700140.. method:: loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100141
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700142 Close the event loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100143
Andriy Maletskyb83d9172018-10-29 23:39:21 +0200144 The loop must not be running when this function is called.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700145 Any pending callbacks will be discarded.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100146
Łukasz Langa7f9a2ae2019-06-04 13:03:20 +0200147 This method clears all queues and shuts down the executor, but does
148 not wait for the executor to finish.
Guido van Rossum41f69f42015-11-19 13:28:47 -0800149
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700150 This method is idempotent and irreversible. No other methods
151 should be called after the event loop is closed.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100152
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700153.. coroutinemethod:: loop.shutdown_asyncgens()
Yury Selivanov03660042016-12-15 17:36:05 -0500154
155 Schedule all currently open :term:`asynchronous generator` objects to
156 close with an :meth:`~agen.aclose()` call. After calling this method,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700157 the event loop will issue a warning if a new asynchronous generator
Carol Willing5b7cbd62018-09-12 17:05:17 -0700158 is iterated. This should be used to reliably finalize all scheduled
Yury Selivanovac94e382018-09-17 23:58:00 -0400159 asynchronous generators.
Carol Willing5b7cbd62018-09-12 17:05:17 -0700160
Yury Selivanovac94e382018-09-17 23:58:00 -0400161 Note that there is no need to call this function when
162 :func:`asyncio.run` is used.
163
164 Example::
Yury Selivanov03660042016-12-15 17:36:05 -0500165
166 try:
167 loop.run_forever()
168 finally:
169 loop.run_until_complete(loop.shutdown_asyncgens())
170 loop.close()
171
172 .. versionadded:: 3.6
173
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400174.. coroutinemethod:: loop.shutdown_default_executor()
175
176 Schedule the closure of the default executor and wait for it to join all of
177 the threads in the :class:`ThreadPoolExecutor`. After calling this method, a
178 :exc:`RuntimeError` will be raised if :meth:`loop.run_in_executor` is called
179 while using the default executor.
180
181 Note that there is no need to call this function when
182 :func:`asyncio.run` is used.
183
184 .. versionadded:: 3.9
185
Yury Selivanov03660042016-12-15 17:36:05 -0500186
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700187Scheduling callbacks
188^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100189
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700190.. method:: loop.call_soon(callback, *args, context=None)
Victor Stinner8464c242014-11-28 13:15:41 +0100191
Carol Willing5b7cbd62018-09-12 17:05:17 -0700192 Schedule a *callback* to be called with *args* arguments at
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700193 the next iteration of the event loop.
Victor Stinner8464c242014-11-28 13:15:41 +0100194
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700195 Callbacks are called in the order in which they are registered.
196 Each callback will be called exactly once.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100197
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700198 An optional keyword-only *context* argument allows specifying a
199 custom :class:`contextvars.Context` for the *callback* to run in.
200 The current context is used when no *context* is provided.
Yury Selivanov28b91782018-05-23 13:35:04 -0400201
Yury Selivanov1096f762015-06-25 13:49:52 -0400202 An instance of :class:`asyncio.Handle` is returned, which can be
Carol Willing5b7cbd62018-09-12 17:05:17 -0700203 used later to cancel the callback.
204
205 This method is not thread-safe.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500206
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700207.. method:: loop.call_soon_threadsafe(callback, *args, context=None)
Victor Stinner8464c242014-11-28 13:15:41 +0100208
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700209 A thread-safe variant of :meth:`call_soon`. Must be used to
210 schedule callbacks *from another thread*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100211
Victor Stinner83704962015-02-25 14:24:15 +0100212 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
213 section of the documentation.
214
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700215.. versionchanged:: 3.7
216 The *context* keyword-only parameter was added. See :pep:`567`
217 for more details.
218
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400219.. _asyncio-pass-keywords:
220
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700221.. note::
222
Carol Willing5b7cbd62018-09-12 17:05:17 -0700223 Most :mod:`asyncio` scheduling functions don't allow passing
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400224 keyword arguments. To do that, use :func:`functools.partial`::
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700225
Carol Willing5b7cbd62018-09-12 17:05:17 -0700226 # will schedule "print("Hello", flush=True)"
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700227 loop.call_soon(
228 functools.partial(print, "Hello", flush=True))
229
230 Using partial objects is usually more convenient than using lambdas,
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400231 as asyncio can render partial objects better in debug and error
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700232 messages.
Yury Selivanov28b91782018-05-23 13:35:04 -0400233
Victor Stinnerea3183f2013-12-03 01:08:00 +0100234
Victor Stinner45b27ed2014-02-01 02:36:43 +0100235.. _asyncio-delayed-calls:
236
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700237Scheduling delayed callbacks
238^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100239
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700240Event loop provides mechanisms to schedule callback functions
241to be called at some point in the future. Event loop uses monotonic
242clocks to track time.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100243
Victor Stinner45b27ed2014-02-01 02:36:43 +0100244
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700245.. method:: loop.call_later(delay, callback, *args, context=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100246
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700247 Schedule *callback* to be called after the given *delay*
248 number of seconds (can be either an int or a float).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100249
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700250 An instance of :class:`asyncio.TimerHandle` is returned which can
251 be used to cancel the callback.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100252
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700253 *callback* will be called exactly once. If two callbacks are
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400254 scheduled for exactly the same time, the order in which they
255 are called is undefined.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100256
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700257 The optional positional *args* will be passed to the callback when
258 it is called. If you want the callback to be called with keyword
259 arguments use :func:`functools.partial`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100260
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700261 An optional keyword-only *context* argument allows specifying a
262 custom :class:`contextvars.Context` for the *callback* to run in.
263 The current context is used when no *context* is provided.
Victor Stinner8464c242014-11-28 13:15:41 +0100264
Yury Selivanov28b91782018-05-23 13:35:04 -0400265 .. versionchanged:: 3.7
266 The *context* keyword-only parameter was added. See :pep:`567`
267 for more details.
268
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400269 .. versionchanged:: 3.8
270 In Python 3.7 and earlier with the default event loop implementation,
271 the *delay* could not exceed one day.
272 This has been fixed in Python 3.8.
273
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700274.. method:: loop.call_at(when, callback, *args, context=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100275
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700276 Schedule *callback* to be called at the given absolute timestamp
277 *when* (an int or a float), using the same time reference as
278 :meth:`loop.time`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100279
280 This method's behavior is the same as :meth:`call_later`.
281
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700282 An instance of :class:`asyncio.TimerHandle` is returned which can
283 be used to cancel the callback.
Victor Stinner8464c242014-11-28 13:15:41 +0100284
Yury Selivanov28b91782018-05-23 13:35:04 -0400285 .. versionchanged:: 3.7
286 The *context* keyword-only parameter was added. See :pep:`567`
287 for more details.
288
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400289 .. versionchanged:: 3.8
290 In Python 3.7 and earlier with the default event loop implementation,
291 the difference between *when* and the current time could not exceed
292 one day. This has been fixed in Python 3.8.
293
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700294.. method:: loop.time()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100295
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700296 Return the current time, as a :class:`float` value, according to
297 the event loop's internal monotonic clock.
298
299.. note::
Enrico Alarico Carbognani7e954e72019-04-18 14:43:14 +0200300 .. versionchanged:: 3.8
301 In Python 3.7 and earlier timeouts (relative *delay* or absolute *when*)
302 should not exceed one day. This has been fixed in Python 3.8.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100303
Victor Stinner3e09e322013-12-03 01:22:06 +0100304.. seealso::
305
306 The :func:`asyncio.sleep` function.
307
Victor Stinnerea3183f2013-12-03 01:08:00 +0100308
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700309Creating Futures and Tasks
310^^^^^^^^^^^^^^^^^^^^^^^^^^
Yury Selivanov950204d2016-05-16 16:23:00 -0400311
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700312.. method:: loop.create_future()
Yury Selivanov950204d2016-05-16 16:23:00 -0400313
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700314 Create an :class:`asyncio.Future` object attached to the event loop.
Yury Selivanov950204d2016-05-16 16:23:00 -0400315
Carol Willing5b7cbd62018-09-12 17:05:17 -0700316 This is the preferred way to create Futures in asyncio. This lets
317 third-party event loops provide alternative implementations of
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700318 the Future object (with better performance or instrumentation).
Yury Selivanov950204d2016-05-16 16:23:00 -0400319
320 .. versionadded:: 3.5.2
321
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700322.. method:: loop.create_task(coro, \*, name=None)
Yury Selivanov950204d2016-05-16 16:23:00 -0400323
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700324 Schedule the execution of a :ref:`coroutine`.
325 Return a :class:`Task` object.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200326
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700327 Third-party event loops can use their own subclass of :class:`Task`
328 for interoperability. In this case, the result type is a subclass
329 of :class:`Task`.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200330
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700331 If the *name* argument is provided and not ``None``, it is set as
332 the name of the task using :meth:`Task.set_name`.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200333
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300334 .. versionchanged:: 3.8
335 Added the ``name`` parameter.
336
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700337.. method:: loop.set_task_factory(factory)
Yury Selivanov71854612015-05-11 16:28:27 -0400338
339 Set a task factory that will be used by
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700340 :meth:`loop.create_task`.
Yury Selivanov71854612015-05-11 16:28:27 -0400341
342 If *factory* is ``None`` the default task factory will be set.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400343 Otherwise, *factory* must be a *callable* with the signature matching
344 ``(loop, coro)``, where *loop* is a reference to the active
345 event loop, and *coro* is a coroutine object. The callable
346 must return a :class:`asyncio.Future`-compatible object.
Yury Selivanov71854612015-05-11 16:28:27 -0400347
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700348.. method:: loop.get_task_factory()
Yury Selivanov71854612015-05-11 16:28:27 -0400349
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700350 Return a task factory or ``None`` if the default one is in use.
Yury Selivanov71854612015-05-11 16:28:27 -0400351
Victor Stinner530ef2f2014-07-08 12:39:10 +0200352
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700353Opening network connections
354^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100355
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700356.. coroutinemethod:: loop.create_connection(protocol_factory, \
357 host=None, port=None, \*, ssl=None, \
358 family=0, proto=0, flags=0, sock=None, \
359 local_addr=None, server_hostname=None, \
360 ssl_handshake_timeout=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100361
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700362 Open a streaming transport connection to a given
363 address specified by *host* and *port*.
364
365 The socket family can be either :py:data:`~socket.AF_INET` or
366 :py:data:`~socket.AF_INET6` depending on *host* (or the *family*
367 argument, if provided).
368
369 The socket type will be :py:data:`~socket.SOCK_STREAM`.
370
371 *protocol_factory* must be a callable returning an
372 :ref:`asyncio protocol <asyncio-protocol>` implementation.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100373
Yury Selivanov19a44f62017-12-14 20:53:26 -0500374 This method will try to establish the connection in the background.
375 When successful, it returns a ``(transport, protocol)`` pair.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100376
377 The chronological synopsis of the underlying operation is as follows:
378
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700379 #. The connection is established and a :ref:`transport <asyncio-transport>`
380 is created for it.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100381
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700382 #. *protocol_factory* is called without arguments and is expected to
383 return a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100384
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700385 #. The protocol instance is coupled with the transport by calling its
386 :meth:`~BaseProtocol.connection_made` method.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100387
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700388 #. A ``(transport, protocol)`` tuple is returned on success.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100389
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700390 The created transport is an implementation-dependent bidirectional
391 stream.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100392
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700393 Other arguments:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100394
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400395 * *ssl*: if given and not false, a SSL/TLS transport is created
Victor Stinnerea3183f2013-12-03 01:08:00 +0100396 (by default a plain TCP transport is created). If *ssl* is
397 a :class:`ssl.SSLContext` object, this context is used to create
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400398 the transport; if *ssl* is :const:`True`, a default context returned
399 from :func:`ssl.create_default_context` is used.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100400
Berker Peksag9c1dba22014-09-28 00:00:58 +0300401 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100402
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400403 * *server_hostname* sets or overrides the hostname that the target
404 server's certificate will be matched against. Should only be passed
405 if *ssl* is not ``None``. By default the value of the *host* argument
Victor Stinnerea3183f2013-12-03 01:08:00 +0100406 is used. If *host* is empty, there is no default and you must pass a
407 value for *server_hostname*. If *server_hostname* is an empty
408 string, hostname matching is disabled (which is a serious security
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400409 risk, allowing for potential man-in-the-middle attacks).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100410
411 * *family*, *proto*, *flags* are the optional address family, protocol
412 and flags to be passed through to getaddrinfo() for *host* resolution.
413 If given, these should all be integers from the corresponding
414 :mod:`socket` module constants.
415
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800416 * *happy_eyeballs_delay*, if given, enables Happy Eyeballs for this
417 connection. It should
418 be a floating-point number representing the amount of time in seconds
419 to wait for a connection attempt to complete, before starting the next
420 attempt in parallel. This is the "Connection Attempt Delay" as defined
421 in :rfc:`8305`. A sensible default value recommended by the RFC is ``0.25``
422 (250 milliseconds).
423
424 * *interleave* controls address reordering when a host name resolves to
425 multiple IP addresses.
426 If ``0`` or unspecified, no reordering is done, and addresses are
427 tried in the order returned by :meth:`getaddrinfo`. If a positive integer
428 is specified, the addresses are interleaved by address family, and the
429 given integer is interpreted as "First Address Family Count" as defined
430 in :rfc:`8305`. The default is ``0`` if *happy_eyeballs_delay* is not
431 specified, and ``1`` if it is.
432
Victor Stinnerea3183f2013-12-03 01:08:00 +0100433 * *sock*, if given, should be an existing, already connected
434 :class:`socket.socket` object to be used by the transport.
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800435 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*,
436 *happy_eyeballs_delay*, *interleave*
Victor Stinnerea3183f2013-12-03 01:08:00 +0100437 and *local_addr* should be specified.
438
439 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
440 to bind the socket to locally. The *local_host* and *local_port*
Carol Willing5b7cbd62018-09-12 17:05:17 -0700441 are looked up using ``getaddrinfo()``, similarly to *host* and *port*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100442
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400443 * *ssl_handshake_timeout* is (for a TLS connection) the time in seconds
444 to wait for the TLS handshake to complete before aborting the connection.
Yury Selivanov96026432018-06-04 11:32:35 -0400445 ``60.0`` seconds if ``None`` (default).
Neil Aspinallf7686c12017-12-19 19:45:42 +0000446
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800447 .. versionadded:: 3.8
448
449 The *happy_eyeballs_delay* and *interleave* parameters.
450
Neil Aspinallf7686c12017-12-19 19:45:42 +0000451 .. versionadded:: 3.7
452
453 The *ssl_handshake_timeout* parameter.
454
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700455 .. versionchanged:: 3.6
456
457 The socket option :py:data:`~socket.TCP_NODELAY` is set by default
458 for all TCP connections.
459
Victor Stinner60208a12015-09-15 22:41:52 +0200460 .. versionchanged:: 3.5
461
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400462 Added support for SSL/TLS in :class:`ProactorEventLoop`.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200463
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100464 .. seealso::
465
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700466 The :func:`open_connection` function is a high-level alternative
467 API. It returns a pair of (:class:`StreamReader`, :class:`StreamWriter`)
468 that can be used directly in async/await code.
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100469
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700470.. coroutinemethod:: loop.create_datagram_endpoint(protocol_factory, \
471 local_addr=None, remote_addr=None, \*, \
472 family=0, proto=0, flags=0, \
473 reuse_address=None, reuse_port=None, \
474 allow_broadcast=None, sock=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100475
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700476 Create a datagram connection.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100477
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700478 The socket family can be either :py:data:`~socket.AF_INET`,
479 :py:data:`~socket.AF_INET6`, or :py:data:`~socket.AF_UNIX`,
480 depending on *host* (or the *family* argument, if provided).
Victor Stinnera6919aa2014-02-19 13:32:34 +0100481
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700482 The socket type will be :py:data:`~socket.SOCK_DGRAM`.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100483
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700484 *protocol_factory* must be a callable returning a
485 :ref:`protocol <asyncio-protocol>` implementation.
486
487 A tuple of ``(transport, protocol)`` is returned on success.
488
489 Other arguments:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700490
491 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
492 to bind the socket to locally. The *local_host* and *local_port*
493 are looked up using :meth:`getaddrinfo`.
494
495 * *remote_addr*, if given, is a ``(remote_host, remote_port)`` tuple used
496 to connect the socket to a remote address. The *remote_host* and
497 *remote_port* are looked up using :meth:`getaddrinfo`.
498
499 * *family*, *proto*, *flags* are the optional address family, protocol
500 and flags to be passed through to :meth:`getaddrinfo` for *host*
501 resolution. If given, these should all be integers from the
502 corresponding :mod:`socket` module constants.
503
504 * *reuse_address* tells the kernel to reuse a local socket in
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700505 ``TIME_WAIT`` state, without waiting for its natural timeout to
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300506 expire. If not specified will automatically be set to ``True`` on
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400507 Unix.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700508
509 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
510 same port as other existing endpoints are bound to, so long as they all
511 set this flag when being created. This option is not supported on Windows
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400512 and some Unixes. If the :py:data:`~socket.SO_REUSEPORT` constant is not
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700513 defined then this capability is unsupported.
514
515 * *allow_broadcast* tells the kernel to allow this endpoint to send
516 messages to the broadcast address.
517
518 * *sock* can optionally be specified in order to use a preexisting,
519 already connected, :class:`socket.socket` object to be used by the
520 transport. If specified, *local_addr* and *remote_addr* should be omitted
521 (must be :const:`None`).
Victor Stinnera6919aa2014-02-19 13:32:34 +0100522
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200523 See :ref:`UDP echo client protocol <asyncio-udp-echo-client-protocol>` and
524 :ref:`UDP echo server protocol <asyncio-udp-echo-server-protocol>` examples.
525
Romuald Brunet0ded5802018-05-14 18:22:00 +0200526 .. versionchanged:: 3.4.4
527 The *family*, *proto*, *flags*, *reuse_address*, *reuse_port,
528 *allow_broadcast*, and *sock* parameters were added.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100529
Andrew Svetlovbafd4b52019-05-28 12:52:15 +0300530 .. versionchanged:: 3.8
531 Added support for Windows.
532
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700533.. coroutinemethod:: loop.create_unix_connection(protocol_factory, \
534 path=None, \*, ssl=None, sock=None, \
535 server_hostname=None, ssl_handshake_timeout=None)
Victor Stinnera6919aa2014-02-19 13:32:34 +0100536
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400537 Create a Unix connection.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100538
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700539 The socket family will be :py:data:`~socket.AF_UNIX`; socket
540 type will be :py:data:`~socket.SOCK_STREAM`.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100541
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700542 A tuple of ``(transport, protocol)`` is returned on success.
Guido van Rossum9e80eeb2016-11-03 14:17:25 -0700543
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400544 *path* is the name of a Unix domain socket and is required,
545 unless a *sock* parameter is specified. Abstract Unix sockets,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700546 :class:`str`, :class:`bytes`, and :class:`~pathlib.Path` paths are
547 supported.
548
549 See the documentation of the :meth:`loop.create_connection` method
550 for information about arguments to this method.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100551
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400552 .. availability:: Unix.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100553
Neil Aspinallf7686c12017-12-19 19:45:42 +0000554 .. versionadded:: 3.7
555
556 The *ssl_handshake_timeout* parameter.
557
Yury Selivanov423fd362017-11-20 17:26:28 -0500558 .. versionchanged:: 3.7
559
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400560 The *path* parameter can now be a :term:`path-like object`.
Yury Selivanov423fd362017-11-20 17:26:28 -0500561
Victor Stinnera6919aa2014-02-19 13:32:34 +0100562
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700563Creating network servers
564^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100565
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700566.. coroutinemethod:: loop.create_server(protocol_factory, \
567 host=None, port=None, \*, \
568 family=socket.AF_UNSPEC, \
569 flags=socket.AI_PASSIVE, \
570 sock=None, backlog=100, ssl=None, \
571 reuse_address=None, reuse_port=None, \
572 ssl_handshake_timeout=None, start_serving=True)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100573
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700574 Create a TCP server (socket type :data:`~socket.SOCK_STREAM`) listening
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400575 on *port* of the *host* address.
Victor Stinner33f6abe2014-10-12 20:36:04 +0200576
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700577 Returns a :class:`Server` object.
Victor Stinner33f6abe2014-10-12 20:36:04 +0200578
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700579 Arguments:
Victor Stinner33f6abe2014-10-12 20:36:04 +0200580
Bumsik Kim5cc583d2018-09-16 19:40:44 -0400581 * *protocol_factory* must be a callable returning a
582 :ref:`protocol <asyncio-protocol>` implementation.
583
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400584 * The *host* parameter can be set to several types which determine where
585 the server would be listening:
586
587 - If *host* is a string, the TCP server is bound to a single network
588 interface specified by *host*.
589
590 - If *host* is a sequence of strings, the TCP server is bound to all
591 network interfaces specified by the sequence.
592
593 - If *host* is an empty string or ``None``, all interfaces are
594 assumed and a list of multiple sockets will be returned (most likely
595 one for IPv4 and another one for IPv6).
Victor Stinner33f6abe2014-10-12 20:36:04 +0200596
597 * *family* can be set to either :data:`socket.AF_INET` or
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700598 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6.
Carol Willing5b7cbd62018-09-12 17:05:17 -0700599 If not set, the *family* will be determined from host name
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700600 (defaults to :data:`~socket.AF_UNSPEC`).
Victor Stinner33f6abe2014-10-12 20:36:04 +0200601
602 * *flags* is a bitmask for :meth:`getaddrinfo`.
603
604 * *sock* can optionally be specified in order to use a preexisting
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400605 socket object. If specified, *host* and *port* must not be specified.
Victor Stinner33f6abe2014-10-12 20:36:04 +0200606
607 * *backlog* is the maximum number of queued connections passed to
608 :meth:`~socket.socket.listen` (defaults to 100).
609
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400610 * *ssl* can be set to an :class:`~ssl.SSLContext` instance to enable
611 TLS over the accepted connections.
Victor Stinner33f6abe2014-10-12 20:36:04 +0200612
613 * *reuse_address* tells the kernel to reuse a local socket in
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700614 ``TIME_WAIT`` state, without waiting for its natural timeout to
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300615 expire. If not specified will automatically be set to ``True`` on
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400616 Unix.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100617
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700618 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
619 same port as other existing endpoints are bound to, so long as they all
620 set this flag when being created. This option is not supported on
621 Windows.
622
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400623 * *ssl_handshake_timeout* is (for a TLS server) the time in seconds to wait
624 for the TLS handshake to complete before aborting the connection.
Yury Selivanov96026432018-06-04 11:32:35 -0400625 ``60.0`` seconds if ``None`` (default).
Neil Aspinallf7686c12017-12-19 19:45:42 +0000626
Yury Selivanovc9070d02018-01-25 18:08:09 -0500627 * *start_serving* set to ``True`` (the default) causes the created server
628 to start accepting connections immediately. When set to ``False``,
629 the user should await on :meth:`Server.start_serving` or
630 :meth:`Server.serve_forever` to make the server to start accepting
631 connections.
632
Neil Aspinallf7686c12017-12-19 19:45:42 +0000633 .. versionadded:: 3.7
634
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700635 Added *ssl_handshake_timeout* and *start_serving* parameters.
636
637 .. versionchanged:: 3.6
638
639 The socket option :py:data:`~socket.TCP_NODELAY` is set by default
640 for all TCP connections.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000641
Victor Stinner60208a12015-09-15 22:41:52 +0200642 .. versionchanged:: 3.5
643
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400644 Added support for SSL/TLS in :class:`ProactorEventLoop`.
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100645
Victor Stinner7b58a2b2015-09-21 18:41:05 +0200646 .. versionchanged:: 3.5.1
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200647
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700648 The *host* parameter can be a sequence of strings.
649
650 .. seealso::
651
652 The :func:`start_server` function is a higher-level alternative API
653 that returns a pair of :class:`StreamReader` and :class:`StreamWriter`
654 that can be used in an async/await code.
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200655
Victor Stinnerea3183f2013-12-03 01:08:00 +0100656
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700657.. coroutinemethod:: loop.create_unix_server(protocol_factory, path=None, \
658 \*, sock=None, backlog=100, ssl=None, \
659 ssl_handshake_timeout=None, start_serving=True)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100660
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700661 Similar to :meth:`loop.create_server` but works with the
662 :py:data:`~socket.AF_UNIX` socket family.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100663
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400664 *path* is the name of a Unix domain socket, and is required,
665 unless a *sock* argument is provided. Abstract Unix sockets,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700666 :class:`str`, :class:`bytes`, and :class:`~pathlib.Path` paths
667 are supported.
Yury Selivanov423fd362017-11-20 17:26:28 -0500668
Bumsik Kim5cc583d2018-09-16 19:40:44 -0400669 See the documentation of the :meth:`loop.create_server` method
670 for information about arguments to this method.
671
Cheryl Sabella2d6097d2018-10-12 10:55:20 -0400672 .. availability:: Unix.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100673
Neil Aspinallf7686c12017-12-19 19:45:42 +0000674 .. versionadded:: 3.7
675
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400676 The *ssl_handshake_timeout* and *start_serving* parameters.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000677
Yury Selivanov423fd362017-11-20 17:26:28 -0500678 .. versionchanged:: 3.7
679
680 The *path* parameter can now be a :class:`~pathlib.Path` object.
681
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700682.. coroutinemethod:: loop.connect_accepted_socket(protocol_factory, \
683 sock, \*, ssl=None, ssl_handshake_timeout=None)
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500684
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700685 Wrap an already accepted connection into a transport/protocol pair.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500686
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700687 This method can be used by servers that accept connections outside
688 of asyncio but that use asyncio to handle them.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500689
690 Parameters:
691
Bumsik Kim5cc583d2018-09-16 19:40:44 -0400692 * *protocol_factory* must be a callable returning a
693 :ref:`protocol <asyncio-protocol>` implementation.
694
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700695 * *sock* is a preexisting socket object returned from
696 :meth:`socket.accept <socket.socket.accept>`.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500697
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700698 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over
699 the accepted connections.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500700
Neil Aspinallf7686c12017-12-19 19:45:42 +0000701 * *ssl_handshake_timeout* is (for an SSL connection) the time in seconds to
702 wait for the SSL handshake to complete before aborting the connection.
Yury Selivanov96026432018-06-04 11:32:35 -0400703 ``60.0`` seconds if ``None`` (default).
Neil Aspinallf7686c12017-12-19 19:45:42 +0000704
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700705 Returns a ``(transport, protocol)`` pair.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100706
Neil Aspinallf7686c12017-12-19 19:45:42 +0000707 .. versionadded:: 3.7
708
709 The *ssl_handshake_timeout* parameter.
710
AraHaan431665b2017-11-21 11:06:26 -0500711 .. versionadded:: 3.5.3
712
713
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700714Transferring files
715^^^^^^^^^^^^^^^^^^
Andrew Svetlov7c684072018-01-27 21:22:47 +0200716
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700717.. coroutinemethod:: loop.sendfile(transport, file, \
718 offset=0, count=None, *, fallback=True)
Andrew Svetlov7c684072018-01-27 21:22:47 +0200719
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700720 Send a *file* over a *transport*. Return the total number of bytes
721 sent.
Andrew Svetlov7c684072018-01-27 21:22:47 +0200722
723 The method uses high-performance :meth:`os.sendfile` if available.
724
725 *file* must be a regular file object opened in binary mode.
726
727 *offset* tells from where to start reading the file. If specified,
728 *count* is the total number of bytes to transmit as opposed to
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400729 sending the file until EOF is reached. File position is always updated,
730 even when this method raises an error, and
731 :meth:`file.tell() <io.IOBase.tell>` can be used to obtain the actual
732 number of bytes sent.
Andrew Svetlov7c684072018-01-27 21:22:47 +0200733
734 *fallback* set to ``True`` makes asyncio to manually read and send
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700735 the file when the platform does not support the sendfile system call
Andrew Svetlov7c684072018-01-27 21:22:47 +0200736 (e.g. Windows or SSL socket on Unix).
737
738 Raise :exc:`SendfileNotAvailableError` if the system does not support
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400739 the *sendfile* syscall and *fallback* is ``False``.
Andrew Svetlov7c684072018-01-27 21:22:47 +0200740
741 .. versionadded:: 3.7
742
743
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500744TLS Upgrade
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700745^^^^^^^^^^^
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500746
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700747.. coroutinemethod:: loop.start_tls(transport, protocol, \
748 sslcontext, \*, server_side=False, \
749 server_hostname=None, ssl_handshake_timeout=None)
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500750
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700751 Upgrade an existing transport-based connection to TLS.
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500752
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700753 Return a new transport instance, that the *protocol* must start using
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500754 immediately after the *await*. The *transport* instance passed to
755 the *start_tls* method should never be used again.
756
757 Parameters:
758
759 * *transport* and *protocol* instances that methods like
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700760 :meth:`~loop.create_server` and
761 :meth:`~loop.create_connection` return.
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500762
763 * *sslcontext*: a configured instance of :class:`~ssl.SSLContext`.
764
765 * *server_side* pass ``True`` when a server-side connection is being
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700766 upgraded (like the one created by :meth:`~loop.create_server`).
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500767
768 * *server_hostname*: sets or overrides the host name that the target
769 server's certificate will be matched against.
770
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400771 * *ssl_handshake_timeout* is (for a TLS connection) the time in seconds to
772 wait for the TLS handshake to complete before aborting the connection.
Yury Selivanov96026432018-06-04 11:32:35 -0400773 ``60.0`` seconds if ``None`` (default).
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500774
775 .. versionadded:: 3.7
776
777
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700778Watching file descriptors
779^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerc1567df2014-02-08 23:22:58 +0100780
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700781.. method:: loop.add_reader(fd, callback, \*args)
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200782
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400783 Start monitoring the *fd* file descriptor for read availability and
784 invoke *callback* with the specified arguments once *fd* is available for
785 reading.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200786
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700787.. method:: loop.remove_reader(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100788
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400789 Stop monitoring the *fd* file descriptor for read availability.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100790
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700791.. method:: loop.add_writer(fd, callback, \*args)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100792
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400793 Start monitoring the *fd* file descriptor for write availability and
794 invoke *callback* with the specified arguments once *fd* is available for
795 writing.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100796
Yury Selivanove247b462018-09-20 12:43:59 -0400797 Use :func:`functools.partial` :ref:`to pass keyword arguments
Naglis17473342018-12-04 09:31:15 +0200798 <asyncio-pass-keywords>` to *callback*.
Victor Stinner8464c242014-11-28 13:15:41 +0100799
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700800.. method:: loop.remove_writer(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100801
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400802 Stop monitoring the *fd* file descriptor for write availability.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100803
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700804See also :ref:`Platform Support <asyncio-platform-support>` section
805for some limitations of these methods.
Victor Stinner04e6df32014-10-11 16:16:27 +0200806
Victor Stinnerc1567df2014-02-08 23:22:58 +0100807
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700808Working with socket objects directly
809^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerc1567df2014-02-08 23:22:58 +0100810
Carol Willing5b7cbd62018-09-12 17:05:17 -0700811In general, protocol implementations that use transport-based APIs
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700812such as :meth:`loop.create_connection` and :meth:`loop.create_server`
813are faster than implementations that work with sockets directly.
Carol Willing5b7cbd62018-09-12 17:05:17 -0700814However, there are some use cases when performance is not critical, and
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700815working with :class:`~socket.socket` objects directly is more
816convenient.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100817
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700818.. coroutinemethod:: loop.sock_recv(sock, nbytes)
Yury Selivanov55c50842016-06-08 12:48:15 -0400819
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400820 Receive up to *nbytes* from *sock*. Asynchronous version of
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700821 :meth:`socket.recv() <socket.socket.recv>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100822
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400823 Return the received data as a bytes object.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700824
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400825 *sock* must be a non-blocking socket.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200826
Yury Selivanov19a44f62017-12-14 20:53:26 -0500827 .. versionchanged:: 3.7
Carol Willing5b7cbd62018-09-12 17:05:17 -0700828 Even though this method was always documented as a coroutine
829 method, releases before Python 3.7 returned a :class:`Future`.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700830 Since Python 3.7 this is an ``async def`` method.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100831
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700832.. coroutinemethod:: loop.sock_recv_into(sock, buf)
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200833
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400834 Receive data from *sock* into the *buf* buffer. Modeled after the blocking
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700835 :meth:`socket.recv_into() <socket.socket.recv_into>` method.
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200836
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700837 Return the number of bytes written to the buffer.
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200838
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400839 *sock* must be a non-blocking socket.
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200840
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200841 .. versionadded:: 3.7
842
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700843.. coroutinemethod:: loop.sock_sendall(sock, data)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100844
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400845 Send *data* to the *sock* socket. Asynchronous version of
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700846 :meth:`socket.sendall() <socket.socket.sendall>`.
Yury Selivanov55c50842016-06-08 12:48:15 -0400847
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400848 This method continues to send to the socket until either all data
849 in *data* has been sent or an error occurs. ``None`` is returned
Carol Willing5b7cbd62018-09-12 17:05:17 -0700850 on success. On error, an exception is raised. Additionally, there is no way
851 to determine how much data, if any, was successfully processed by the
852 receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100853
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400854 *sock* must be a non-blocking socket.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200855
Yury Selivanov19a44f62017-12-14 20:53:26 -0500856 .. versionchanged:: 3.7
857 Even though the method was always documented as a coroutine
858 method, before Python 3.7 it returned an :class:`Future`.
859 Since Python 3.7, this is an ``async def`` method.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100860
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700861.. coroutinemethod:: loop.sock_connect(sock, address)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100862
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400863 Connect *sock* to a remote socket at *address*.
Victor Stinner1b0580b2014-02-13 09:24:37 +0100864
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700865 Asynchronous version of :meth:`socket.connect() <socket.socket.connect>`.
866
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400867 *sock* must be a non-blocking socket.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200868
Yury Selivanov55c50842016-06-08 12:48:15 -0400869 .. versionchanged:: 3.5.2
870 ``address`` no longer needs to be resolved. ``sock_connect``
871 will try to check if the *address* is already resolved by calling
872 :func:`socket.inet_pton`. If not,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700873 :meth:`loop.getaddrinfo` will be used to resolve the
Yury Selivanov55c50842016-06-08 12:48:15 -0400874 *address*.
875
Victor Stinnerc1567df2014-02-08 23:22:58 +0100876 .. seealso::
877
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700878 :meth:`loop.create_connection`
Yury Selivanov55c50842016-06-08 12:48:15 -0400879 and :func:`asyncio.open_connection() <open_connection>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100880
881
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700882.. coroutinemethod:: loop.sock_accept(sock)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100883
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700884 Accept a connection. Modeled after the blocking
885 :meth:`socket.accept() <socket.socket.accept>` method.
Yury Selivanov55c50842016-06-08 12:48:15 -0400886
887 The socket must be bound to an address and listening
Victor Stinnerc1567df2014-02-08 23:22:58 +0100888 for connections. The return value is a pair ``(conn, address)`` where *conn*
889 is a *new* socket object usable to send and receive data on the connection,
890 and *address* is the address bound to the socket on the other end of the
891 connection.
892
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400893 *sock* must be a non-blocking socket.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200894
Yury Selivanov19a44f62017-12-14 20:53:26 -0500895 .. versionchanged:: 3.7
896 Even though the method was always documented as a coroutine
897 method, before Python 3.7 it returned a :class:`Future`.
898 Since Python 3.7, this is an ``async def`` method.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100899
900 .. seealso::
901
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700902 :meth:`loop.create_server` and :func:`start_server`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100903
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700904.. coroutinemethod:: loop.sock_sendfile(sock, file, offset=0, count=None, \
905 \*, fallback=True)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200906
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700907 Send a file using high-performance :mod:`os.sendfile` if possible.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400908 Return the total number of bytes sent.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200909
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700910 Asynchronous version of :meth:`socket.sendfile() <socket.socket.sendfile>`.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200911
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400912 *sock* must be a non-blocking :const:`socket.SOCK_STREAM`
913 :class:`~socket.socket`.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200914
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400915 *file* must be a regular file object open in binary mode.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200916
917 *offset* tells from where to start reading the file. If specified,
918 *count* is the total number of bytes to transmit as opposed to
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400919 sending the file until EOF is reached. File position is always updated,
920 even when this method raises an error, and
921 :meth:`file.tell() <io.IOBase.tell>` can be used to obtain the actual
922 number of bytes sent.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200923
Carol Willing5b7cbd62018-09-12 17:05:17 -0700924 *fallback*, when set to ``True``, makes asyncio manually read and send
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200925 the file when the platform does not support the sendfile syscall
926 (e.g. Windows or SSL socket on Unix).
927
Andrew Svetlov7464e872018-01-19 20:04:29 +0200928 Raise :exc:`SendfileNotAvailableError` if the system does not support
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200929 *sendfile* syscall and *fallback* is ``False``.
930
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400931 *sock* must be a non-blocking socket.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700932
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200933 .. versionadded:: 3.7
934
Victor Stinnerc1567df2014-02-08 23:22:58 +0100935
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700936DNS
937^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100938
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700939.. coroutinemethod:: loop.getaddrinfo(host, port, \*, family=0, \
940 type=0, proto=0, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100941
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700942 Asynchronous version of :meth:`socket.getaddrinfo`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100943
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700944.. coroutinemethod:: loop.getnameinfo(sockaddr, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100945
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700946 Asynchronous version of :meth:`socket.getnameinfo`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100947
Yury Selivanovbec23722018-01-28 14:09:40 -0500948.. versionchanged:: 3.7
949 Both *getaddrinfo* and *getnameinfo* methods were always documented
950 to return a coroutine, but prior to Python 3.7 they were, in fact,
951 returning :class:`asyncio.Future` objects. Starting with Python 3.7
952 both methods are coroutines.
953
Victor Stinnerea3183f2013-12-03 01:08:00 +0100954
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700955Working with pipes
956^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100957
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700958.. coroutinemethod:: loop.connect_read_pipe(protocol_factory, pipe)
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200959
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400960 Register the read end of *pipe* in the event loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100961
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700962 *protocol_factory* must be a callable returning an
963 :ref:`asyncio protocol <asyncio-protocol>` implementation.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100964
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700965 *pipe* is a :term:`file-like object <file object>`.
966
967 Return pair ``(transport, protocol)``, where *transport* supports
Bumsik Kim5cc583d2018-09-16 19:40:44 -0400968 the :class:`ReadTransport` interface and *protocol* is an object
969 instantiated by the *protocol_factory*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100970
Victor Stinnerd84fd732014-08-26 01:01:59 +0200971 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
972 non-blocking mode.
973
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700974.. coroutinemethod:: loop.connect_write_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100975
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400976 Register the write end of *pipe* in the event loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100977
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700978 *protocol_factory* must be a callable returning an
979 :ref:`asyncio protocol <asyncio-protocol>` implementation.
980
981 *pipe* is :term:`file-like object <file object>`.
982
Victor Stinner2cef3002014-10-23 22:38:46 +0200983 Return pair ``(transport, protocol)``, where *transport* supports
Bumsik Kim5cc583d2018-09-16 19:40:44 -0400984 :class:`WriteTransport` interface and *protocol* is an object
985 instantiated by the *protocol_factory*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100986
Victor Stinnerd84fd732014-08-26 01:01:59 +0200987 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
988 non-blocking mode.
989
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700990.. note::
991
992 :class:`SelectorEventLoop` does not support the above methods on
Carol Willing5b7cbd62018-09-12 17:05:17 -0700993 Windows. Use :class:`ProactorEventLoop` instead for Windows.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700994
Victor Stinner08444382014-02-02 22:43:39 +0100995.. seealso::
996
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700997 The :meth:`loop.subprocess_exec` and
998 :meth:`loop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100999
Victor Stinnerea3183f2013-12-03 01:08:00 +01001000
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001001Unix signals
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001002^^^^^^^^^^^^
Victor Stinner8b863482014-01-27 10:07:50 +01001003
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001004.. method:: loop.add_signal_handler(signum, callback, \*args)
Victor Stinner8b863482014-01-27 10:07:50 +01001005
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001006 Set *callback* as the handler for the *signum* signal.
Victor Stinner8b863482014-01-27 10:07:50 +01001007
Hrvoje Nikšiće3666fc2018-12-18 22:31:29 +01001008 The callback will be invoked by *loop*, along with other queued callbacks
1009 and runnable coroutines of that event loop. Unlike signal handlers
1010 registered using :func:`signal.signal`, a callback registered with this
1011 function is allowed to interact with the event loop.
1012
Victor Stinner8b863482014-01-27 10:07:50 +01001013 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
1014 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
1015
Yury Selivanove247b462018-09-20 12:43:59 -04001016 Use :func:`functools.partial` :ref:`to pass keyword arguments
Naglis17473342018-12-04 09:31:15 +02001017 <asyncio-pass-keywords>` to *callback*.
Victor Stinner8464c242014-11-28 13:15:41 +01001018
Hrvoje Nikšiće3666fc2018-12-18 22:31:29 +01001019 Like :func:`signal.signal`, this function must be invoked in the main
1020 thread.
1021
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001022.. method:: loop.remove_signal_handler(sig)
Victor Stinner8b863482014-01-27 10:07:50 +01001023
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001024 Remove the handler for the *sig* signal.
Victor Stinner8b863482014-01-27 10:07:50 +01001025
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001026 Return ``True`` if the signal handler was removed, or ``False`` if
1027 no handler was set for the given signal.
Victor Stinner8b863482014-01-27 10:07:50 +01001028
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001029 .. availability:: Unix.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001030
Victor Stinner8b863482014-01-27 10:07:50 +01001031.. seealso::
1032
1033 The :mod:`signal` module.
1034
1035
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001036Executing code in thread or process pools
1037^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +01001038
Yury Selivanov47150392018-09-18 17:55:44 -04001039.. awaitablemethod:: loop.run_in_executor(executor, func, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +01001040
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001041 Arrange for *func* to be called in the specified executor.
Victor Stinnerea3183f2013-12-03 01:08:00 +01001042
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001043 The *executor* argument should be an :class:`concurrent.futures.Executor`
Larry Hastings3732ed22014-03-15 21:13:56 -07001044 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +01001045
Yury Selivanove247b462018-09-20 12:43:59 -04001046 Example::
1047
1048 import asyncio
1049 import concurrent.futures
1050
1051 def blocking_io():
1052 # File operations (such as logging) can block the
1053 # event loop: run them in a thread pool.
1054 with open('/dev/urandom', 'rb') as f:
1055 return f.read(100)
1056
1057 def cpu_bound():
1058 # CPU-bound operations will block the event loop:
1059 # in general it is preferable to run them in a
1060 # process pool.
1061 return sum(i * i for i in range(10 ** 7))
1062
1063 async def main():
1064 loop = asyncio.get_running_loop()
1065
1066 ## Options:
1067
1068 # 1. Run in the default loop's executor:
1069 result = await loop.run_in_executor(
1070 None, blocking_io)
1071 print('default thread pool', result)
1072
1073 # 2. Run in a custom thread pool:
1074 with concurrent.futures.ThreadPoolExecutor() as pool:
1075 result = await loop.run_in_executor(
1076 pool, blocking_io)
1077 print('custom thread pool', result)
1078
1079 # 3. Run in a custom process pool:
1080 with concurrent.futures.ProcessPoolExecutor() as pool:
1081 result = await loop.run_in_executor(
1082 pool, cpu_bound)
1083 print('custom process pool', result)
1084
1085 asyncio.run(main())
Victor Stinner8464c242014-11-28 13:15:41 +01001086
Yury Selivanovbec23722018-01-28 14:09:40 -05001087 This method returns a :class:`asyncio.Future` object.
1088
Yury Selivanove247b462018-09-20 12:43:59 -04001089 Use :func:`functools.partial` :ref:`to pass keyword arguments
1090 <asyncio-pass-keywords>` to *func*.
1091
Yury Selivanove8a60452016-10-21 17:40:42 -04001092 .. versionchanged:: 3.5.3
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001093 :meth:`loop.run_in_executor` no longer configures the
Yury Selivanove8a60452016-10-21 17:40:42 -04001094 ``max_workers`` of the thread pool executor it creates, instead
1095 leaving it up to the thread pool executor
1096 (:class:`~concurrent.futures.ThreadPoolExecutor`) to set the
1097 default.
1098
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001099.. method:: loop.set_default_executor(executor)
Victor Stinnerea3183f2013-12-03 01:08:00 +01001100
Elvis Pranskevichus22d25082018-07-30 11:42:43 +01001101 Set *executor* as the default executor used by :meth:`run_in_executor`.
1102 *executor* should be an instance of
1103 :class:`~concurrent.futures.ThreadPoolExecutor`.
1104
1105 .. deprecated:: 3.8
1106 Using an executor that is not an instance of
1107 :class:`~concurrent.futures.ThreadPoolExecutor` is deprecated and
1108 will trigger an error in Python 3.9.
Victor Stinnerea3183f2013-12-03 01:08:00 +01001109
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001110 *executor* must be an instance of
1111 :class:`concurrent.futures.ThreadPoolExecutor`.
1112
Victor Stinnerea3183f2013-12-03 01:08:00 +01001113
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001114Error Handling API
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001115^^^^^^^^^^^^^^^^^^
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001116
Martin Panterc04fb562016-02-10 05:44:01 +00001117Allows customizing how exceptions are handled in the event loop.
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001118
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001119.. method:: loop.set_exception_handler(handler)
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001120
1121 Set *handler* as the new event loop exception handler.
1122
1123 If *handler* is ``None``, the default exception handler will
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001124 be set. Otherwise, *handler* must be a callable with the signature
1125 matching ``(loop, context)``, where ``loop``
1126 is a reference to the active event loop, and ``context``
1127 is a ``dict`` object containing the details of the exception
1128 (see :meth:`call_exception_handler` documentation for details
1129 about context).
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001130
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001131.. method:: loop.get_exception_handler()
Yury Selivanov950204d2016-05-16 16:23:00 -04001132
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001133 Return the current exception handler, or ``None`` if no custom
1134 exception handler was set.
Yury Selivanov950204d2016-05-16 16:23:00 -04001135
1136 .. versionadded:: 3.5.2
1137
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001138.. method:: loop.default_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001139
1140 Default exception handler.
1141
1142 This is called when an exception occurs and no exception
Carol Willing5b7cbd62018-09-12 17:05:17 -07001143 handler is set. This can be called by a custom exception
1144 handler that wants to defer to the default handler behavior.
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001145
1146 *context* parameter has the same meaning as in
1147 :meth:`call_exception_handler`.
1148
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001149.. method:: loop.call_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001150
1151 Call the current event loop exception handler.
1152
1153 *context* is a ``dict`` object containing the following keys
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001154 (new keys may be introduced in future Python versions):
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001155
1156 * 'message': Error message;
1157 * 'exception' (optional): Exception object;
1158 * 'future' (optional): :class:`asyncio.Future` instance;
1159 * 'handle' (optional): :class:`asyncio.Handle` instance;
1160 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
1161 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
1162 * 'socket' (optional): :class:`socket.socket` instance.
1163
1164 .. note::
1165
Carol Willing5b7cbd62018-09-12 17:05:17 -07001166 This method should not be overloaded in subclassed
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001167 event loops. For custom exception handling, use
1168 the :meth:`set_exception_handler()` method.
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001169
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001170Enabling debug mode
1171^^^^^^^^^^^^^^^^^^^
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001172
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001173.. method:: loop.get_debug()
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001174
Victor Stinner7b7120e2014-06-23 00:12:14 +02001175 Get the debug mode (:class:`bool`) of the event loop.
1176
1177 The default value is ``True`` if the environment variable
1178 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
1179 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001180
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001181.. method:: loop.set_debug(enabled: bool)
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001182
1183 Set the debug mode of the event loop.
1184
Yury Selivanov805e27e2018-09-14 16:57:11 -07001185 .. versionchanged:: 3.7
1186
1187 The new ``-X dev`` command line option can now also be used
1188 to enable the debug mode.
1189
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001190.. seealso::
1191
Victor Stinner62511fd2014-06-23 00:36:11 +02001192 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001193
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001194
1195Running Subprocesses
1196^^^^^^^^^^^^^^^^^^^^
1197
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001198Methods described in this subsections are low-level. In regular
1199async/await code consider using the high-level
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001200:func:`asyncio.create_subprocess_shell` and
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001201:func:`asyncio.create_subprocess_exec` convenience functions instead.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001202
1203.. note::
1204
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001205 The default asyncio event loop on **Windows** does not support
1206 subprocesses. See :ref:`Subprocess Support on Windows
1207 <asyncio-windows-subprocess>` for details.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001208
1209.. coroutinemethod:: loop.subprocess_exec(protocol_factory, \*args, \
1210 stdin=subprocess.PIPE, stdout=subprocess.PIPE, \
1211 stderr=subprocess.PIPE, \*\*kwargs)
1212
1213 Create a subprocess from one or more string arguments specified by
1214 *args*.
1215
1216 *args* must be a list of strings represented by:
1217
1218 * :class:`str`;
1219 * or :class:`bytes`, encoded to the
1220 :ref:`filesystem encoding <filesystem-encoding>`.
1221
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001222 The first string specifies the program executable,
Carol Willing5b7cbd62018-09-12 17:05:17 -07001223 and the remaining strings specify the arguments. Together, string
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001224 arguments form the ``argv`` of the program.
1225
1226 This is similar to the standard library :class:`subprocess.Popen`
1227 class called with ``shell=False`` and the list of strings passed as
1228 the first argument; however, where :class:`~subprocess.Popen` takes
1229 a single argument which is list of strings, *subprocess_exec*
1230 takes multiple string arguments.
1231
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001232 The *protocol_factory* must be a callable returning a subclass of the
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001233 :class:`asyncio.SubprocessProtocol` class.
1234
1235 Other parameters:
1236
sbstpf0d4c642019-05-27 19:51:19 -04001237 * *stdin* can be any of these:
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001238
sbstpf0d4c642019-05-27 19:51:19 -04001239 * a file-like object representing a pipe to be connected to the
1240 subprocess's standard input stream using
1241 :meth:`~loop.connect_write_pipe`
1242 * the :const:`subprocess.PIPE` constant (default) which will create a new
1243 pipe and connect it,
1244 * the value ``None`` which will make the subprocess inherit the file
1245 descriptor from this process
1246 * the :const:`subprocess.DEVNULL` constant which indicates that the
1247 special :data:`os.devnull` file will be used
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001248
sbstpf0d4c642019-05-27 19:51:19 -04001249 * *stdout* can be any of these:
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001250
sbstpf0d4c642019-05-27 19:51:19 -04001251 * a file-like object representing a pipe to be connected to the
1252 subprocess's standard output stream using
1253 :meth:`~loop.connect_write_pipe`
1254 * the :const:`subprocess.PIPE` constant (default) which will create a new
1255 pipe and connect it,
1256 * the value ``None`` which will make the subprocess inherit the file
1257 descriptor from this process
1258 * the :const:`subprocess.DEVNULL` constant which indicates that the
1259 special :data:`os.devnull` file will be used
1260
1261 * *stderr* can be any of these:
1262
1263 * a file-like object representing a pipe to be connected to the
1264 subprocess's standard error stream using
1265 :meth:`~loop.connect_write_pipe`
1266 * the :const:`subprocess.PIPE` constant (default) which will create a new
1267 pipe and connect it,
1268 * the value ``None`` which will make the subprocess inherit the file
1269 descriptor from this process
1270 * the :const:`subprocess.DEVNULL` constant which indicates that the
1271 special :data:`os.devnull` file will be used
1272 * the :const:`subprocess.STDOUT` constant which will connect the standard
1273 error stream to the process' standard output stream
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001274
1275 * All other keyword arguments are passed to :class:`subprocess.Popen`
sbstpf0d4c642019-05-27 19:51:19 -04001276 without interpretation, except for *bufsize*, *universal_newlines*,
1277 *shell*, *text*, *encoding* and *errors*, which should not be specified
1278 at all.
1279
1280 The ``asyncio`` subprocess API does not support decoding the streams
1281 as text. :func:`bytes.decode` can be used to convert the bytes returned
1282 from the stream to text.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001283
1284 See the constructor of the :class:`subprocess.Popen` class
1285 for documentation on other arguments.
1286
1287 Returns a pair of ``(transport, protocol)``, where *transport*
Bumsik Kim5cc583d2018-09-16 19:40:44 -04001288 conforms to the :class:`asyncio.SubprocessTransport` base class and
1289 *protocol* is an object instantiated by the *protocol_factory*.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001290
1291.. coroutinemethod:: loop.subprocess_shell(protocol_factory, cmd, \*, \
1292 stdin=subprocess.PIPE, stdout=subprocess.PIPE, \
1293 stderr=subprocess.PIPE, \*\*kwargs)
1294
1295 Create a subprocess from *cmd*, which can be a :class:`str` or a
1296 :class:`bytes` string encoded to the
1297 :ref:`filesystem encoding <filesystem-encoding>`,
1298 using the platform's "shell" syntax.
1299
1300 This is similar to the standard library :class:`subprocess.Popen`
1301 class called with ``shell=True``.
1302
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001303 The *protocol_factory* must be a callable returning a subclass of the
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001304 :class:`SubprocessProtocol` class.
1305
1306 See :meth:`~loop.subprocess_exec` for more details about
1307 the remaining arguments.
1308
1309 Returns a pair of ``(transport, protocol)``, where *transport*
Bumsik Kim5cc583d2018-09-16 19:40:44 -04001310 conforms to the :class:`SubprocessTransport` base class and
1311 *protocol* is an object instantiated by the *protocol_factory*.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001312
1313.. note::
1314 It is the application's responsibility to ensure that all whitespace
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001315 and special characters are quoted appropriately to avoid `shell injection
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001316 <https://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_
1317 vulnerabilities. The :func:`shlex.quote` function can be used to
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001318 properly escape whitespace and special characters in strings that
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001319 are going to be used to construct shell commands.
1320
1321
1322Callback Handles
1323================
1324
1325.. class:: Handle
1326
1327 A callback wrapper object returned by :meth:`loop.call_soon`,
1328 :meth:`loop.call_soon_threadsafe`.
1329
1330 .. method:: cancel()
1331
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001332 Cancel the callback. If the callback has already been canceled
1333 or executed, this method has no effect.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001334
1335 .. method:: cancelled()
1336
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001337 Return ``True`` if the callback was cancelled.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001338
1339 .. versionadded:: 3.7
1340
1341.. class:: TimerHandle
1342
1343 A callback wrapper object returned by :meth:`loop.call_later`,
1344 and :meth:`loop.call_at`.
1345
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001346 This class is a subclass of :class:`Handle`.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001347
1348 .. method:: when()
1349
1350 Return a scheduled callback time as :class:`float` seconds.
1351
1352 The time is an absolute timestamp, using the same time
1353 reference as :meth:`loop.time`.
1354
1355 .. versionadded:: 3.7
1356
1357
1358Server Objects
1359==============
1360
1361Server objects are created by :meth:`loop.create_server`,
1362:meth:`loop.create_unix_server`, :func:`start_server`,
1363and :func:`start_unix_server` functions.
1364
1365Do not instantiate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +01001366
Victor Stinner8ebeb032014-07-11 23:47:40 +02001367.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +01001368
Yury Selivanovc9070d02018-01-25 18:08:09 -05001369 *Server* objects are asynchronous context managers. When used in an
1370 ``async with`` statement, it's guaranteed that the Server object is
1371 closed and not accepting new connections when the ``async with``
1372 statement is completed::
1373
1374 srv = await loop.create_server(...)
1375
1376 async with srv:
1377 # some code
1378
Carol Willing5b7cbd62018-09-12 17:05:17 -07001379 # At this point, srv is closed and no longer accepts new connections.
Yury Selivanovc9070d02018-01-25 18:08:09 -05001380
1381
1382 .. versionchanged:: 3.7
1383 Server object is an asynchronous context manager since Python 3.7.
Victor Stinner8c462c52014-01-24 18:11:43 +01001384
1385 .. method:: close()
1386
Victor Stinner4bfb14a2014-07-12 03:20:24 +02001387 Stop serving: close listening sockets and set the :attr:`sockets`
1388 attribute to ``None``.
1389
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001390 The sockets that represent existing incoming client connections
1391 are left open.
Victor Stinner8ebeb032014-07-11 23:47:40 +02001392
Berker Peksag49c9edf2016-01-20 07:14:22 +02001393 The server is closed asynchronously, use the :meth:`wait_closed`
1394 coroutine to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +01001395
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +05301396 .. method:: get_loop()
1397
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001398 Return the event loop associated with the server object.
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +05301399
1400 .. versionadded:: 3.7
1401
Yury Selivanovc9070d02018-01-25 18:08:09 -05001402 .. coroutinemethod:: start_serving()
1403
1404 Start accepting connections.
1405
1406 This method is idempotent, so it can be called when
1407 the server is already being serving.
1408
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001409 The *start_serving* keyword-only parameter to
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001410 :meth:`loop.create_server` and
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001411 :meth:`asyncio.start_server` allows creating a Server object
1412 that is not accepting connections initially. In this case
1413 ``Server.start_serving()``, or :meth:`Server.serve_forever` can be used
1414 to make the Server start accepting connections.
Yury Selivanovc9070d02018-01-25 18:08:09 -05001415
1416 .. versionadded:: 3.7
1417
1418 .. coroutinemethod:: serve_forever()
1419
1420 Start accepting connections until the coroutine is cancelled.
1421 Cancellation of ``serve_forever`` task causes the server
1422 to be closed.
1423
1424 This method can be called if the server is already accepting
1425 connections. Only one ``serve_forever`` task can exist per
1426 one *Server* object.
1427
1428 Example::
1429
1430 async def client_connected(reader, writer):
1431 # Communicate with the client with
1432 # reader/writer streams. For example:
1433 await reader.readline()
1434
1435 async def main(host, port):
1436 srv = await asyncio.start_server(
1437 client_connected, host, port)
Andrew Svetlov17ab8f02018-02-17 19:44:35 +02001438 await srv.serve_forever()
Yury Selivanovc9070d02018-01-25 18:08:09 -05001439
1440 asyncio.run(main('127.0.0.1', 0))
1441
1442 .. versionadded:: 3.7
1443
1444 .. method:: is_serving()
1445
1446 Return ``True`` if the server is accepting new connections.
1447
1448 .. versionadded:: 3.7
1449
Victor Stinnerbdd574d2015-02-12 22:49:18 +01001450 .. coroutinemethod:: wait_closed()
Victor Stinner8c462c52014-01-24 18:11:43 +01001451
Victor Stinner8ebeb032014-07-11 23:47:40 +02001452 Wait until the :meth:`close` method completes.
1453
Victor Stinner8ebeb032014-07-11 23:47:40 +02001454 .. attribute:: sockets
1455
Emmanuel Ariasdf5cdc12019-02-22 14:34:41 -03001456 List of :class:`socket.socket` objects the server is listening on.
Victor Stinner8c462c52014-01-24 18:11:43 +01001457
Yury Selivanovc9070d02018-01-25 18:08:09 -05001458 .. versionchanged:: 3.7
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001459 Prior to Python 3.7 ``Server.sockets`` used to return an
1460 internal list of server sockets directly. In 3.7 a copy
Yury Selivanovc9070d02018-01-25 18:08:09 -05001461 of that list is returned.
1462
Victor Stinner8c462c52014-01-24 18:11:43 +01001463
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001464.. _asyncio-event-loops:
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001465
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001466Event Loop Implementations
1467==========================
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001468
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001469asyncio ships with two different event loop implementations:
1470:class:`SelectorEventLoop` and :class:`ProactorEventLoop`.
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001471
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001472By default asyncio is configured to use :class:`SelectorEventLoop`
Ben Darnell9ffca672019-06-22 13:38:21 -04001473on Unix and :class:`ProactorEventLoop` on Windows.
Andrew Svetlov3d4dbd82018-02-01 19:59:32 +02001474
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001475
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001476.. class:: SelectorEventLoop
1477
1478 An event loop based on the :mod:`selectors` module.
1479
1480 Uses the most efficient *selector* available for the given
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001481 platform. It is also possible to manually configure the
1482 exact selector implementation to be used::
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001483
1484 import asyncio
1485 import selectors
1486
1487 selector = selectors.SelectSelector()
1488 loop = asyncio.SelectorEventLoop(selector)
1489 asyncio.set_event_loop(loop)
Andrew Svetlov7464e872018-01-19 20:04:29 +02001490
1491
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001492 .. availability:: Unix, Windows.
Andrew Svetlov7464e872018-01-19 20:04:29 +02001493
1494
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001495.. class:: ProactorEventLoop
1496
1497 An event loop for Windows that uses "I/O Completion Ports" (IOCP).
1498
Cheryl Sabella2d6097d2018-10-12 10:55:20 -04001499 .. availability:: Windows.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001500
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001501 .. seealso::
1502
1503 `MSDN documentation on I/O Completion Ports
1504 <https://docs.microsoft.com/en-ca/windows/desktop/FileIO/i-o-completion-ports>`_.
1505
1506
1507.. class:: AbstractEventLoop
1508
1509 Abstract base class for asyncio-compliant event loops.
1510
1511 The :ref:`Event Loop Methods <asyncio-event-loop>` section lists all
1512 methods that an alternative implementation of ``AbstractEventLoop``
1513 should have defined.
1514
1515
1516Examples
1517========
1518
1519Note that all examples in this section **purposefully** show how
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001520to use the low-level event loop APIs, such as :meth:`loop.run_forever`
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001521and :meth:`loop.call_soon`. Modern asyncio applications rarely
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001522need to be written this way; consider using the high-level functions
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001523like :func:`asyncio.run`.
1524
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001525
Yury Selivanov394374e2018-09-17 15:35:24 -04001526.. _asyncio_example_lowlevel_helloworld:
Victor Stinnerea3183f2013-12-03 01:08:00 +01001527
Victor Stinner7f314ed2014-10-15 18:49:16 +02001528Hello World with call_soon()
Victor Stinnera092a612015-01-09 15:58:41 +01001529^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +01001530
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001531An example using the :meth:`loop.call_soon` method to schedule a
1532callback. The callback displays ``"Hello World"`` and then stops the
1533event loop::
Victor Stinnerea3183f2013-12-03 01:08:00 +01001534
1535 import asyncio
1536
Victor Stinner7f314ed2014-10-15 18:49:16 +02001537 def hello_world(loop):
Carol Willing5b7cbd62018-09-12 17:05:17 -07001538 """A callback to print 'Hello World' and stop the event loop"""
Victor Stinnerea3183f2013-12-03 01:08:00 +01001539 print('Hello World')
Victor Stinner7f314ed2014-10-15 18:49:16 +02001540 loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +01001541
1542 loop = asyncio.get_event_loop()
Victor Stinner7f314ed2014-10-15 18:49:16 +02001543
1544 # Schedule a call to hello_world()
1545 loop.call_soon(hello_world, loop)
1546
1547 # Blocking call interrupted by loop.stop()
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001548 try:
1549 loop.run_forever()
1550 finally:
1551 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +01001552
Victor Stinner3e09e322013-12-03 01:22:06 +01001553.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +01001554
Yury Selivanov3faaa882018-09-14 13:32:07 -07001555 A similar :ref:`Hello World <coroutine>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001556 example created with a coroutine and the :func:`run` function.
Victor Stinnerea3183f2013-12-03 01:08:00 +01001557
Victor Stinner8b863482014-01-27 10:07:50 +01001558
Yury Selivanov394374e2018-09-17 15:35:24 -04001559.. _asyncio_example_call_later:
Victor Stinner7f314ed2014-10-15 18:49:16 +02001560
1561Display the current date with call_later()
Victor Stinnera092a612015-01-09 15:58:41 +01001562^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner7f314ed2014-10-15 18:49:16 +02001563
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001564An example of a callback displaying the current date every second. The
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001565callback uses the :meth:`loop.call_later` method to reschedule itself
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001566after 5 seconds, and then stops the event loop::
Victor Stinner7f314ed2014-10-15 18:49:16 +02001567
1568 import asyncio
1569 import datetime
1570
1571 def display_date(end_time, loop):
1572 print(datetime.datetime.now())
1573 if (loop.time() + 1.0) < end_time:
1574 loop.call_later(1, display_date, end_time, loop)
1575 else:
1576 loop.stop()
1577
1578 loop = asyncio.get_event_loop()
1579
1580 # Schedule the first call to display_date()
1581 end_time = loop.time() + 5.0
1582 loop.call_soon(display_date, end_time, loop)
1583
1584 # Blocking call interrupted by loop.stop()
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001585 try:
1586 loop.run_forever()
1587 finally:
1588 loop.close()
Victor Stinner7f314ed2014-10-15 18:49:16 +02001589
1590.. seealso::
1591
Yury Selivanov7372c3b2018-09-14 15:11:24 -07001592 A similar :ref:`current date <asyncio_example_sleep>` example
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001593 created with a coroutine and the :func:`run` function.
Victor Stinner7f314ed2014-10-15 18:49:16 +02001594
1595
Yury Selivanov394374e2018-09-17 15:35:24 -04001596.. _asyncio_example_watch_fd:
Victor Stinner8b863482014-01-27 10:07:50 +01001597
Victor Stinner04e6df32014-10-11 16:16:27 +02001598Watch a file descriptor for read events
Victor Stinnera092a612015-01-09 15:58:41 +01001599^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +02001600
1601Wait until a file descriptor received some data using the
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001602:meth:`loop.add_reader` method and then close the event loop::
Victor Stinner04e6df32014-10-11 16:16:27 +02001603
1604 import asyncio
Victor Stinnerac577d72017-11-28 21:33:20 +01001605 from socket import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +02001606
1607 # Create a pair of connected file descriptors
Victor Stinnerccd8e342014-10-11 16:30:02 +02001608 rsock, wsock = socketpair()
Carol Willing5b7cbd62018-09-12 17:05:17 -07001609
Victor Stinner04e6df32014-10-11 16:16:27 +02001610 loop = asyncio.get_event_loop()
1611
1612 def reader():
1613 data = rsock.recv(100)
1614 print("Received:", data.decode())
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001615
Victor Stinner2cef3002014-10-23 22:38:46 +02001616 # We are done: unregister the file descriptor
Victor Stinner04e6df32014-10-11 16:16:27 +02001617 loop.remove_reader(rsock)
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001618
Victor Stinner04e6df32014-10-11 16:16:27 +02001619 # Stop the event loop
1620 loop.stop()
1621
Victor Stinner2cef3002014-10-23 22:38:46 +02001622 # Register the file descriptor for read event
Victor Stinner04e6df32014-10-11 16:16:27 +02001623 loop.add_reader(rsock, reader)
1624
1625 # Simulate the reception of data from the network
1626 loop.call_soon(wsock.send, 'abc'.encode())
1627
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001628 try:
1629 # Run the event loop
1630 loop.run_forever()
1631 finally:
Carol Willing5b7cbd62018-09-12 17:05:17 -07001632 # We are done. Close sockets and the event loop.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001633 rsock.close()
1634 wsock.close()
1635 loop.close()
Victor Stinner04e6df32014-10-11 16:16:27 +02001636
1637.. seealso::
1638
Yury Selivanov394374e2018-09-17 15:35:24 -04001639 * A similar :ref:`example <asyncio_example_create_connection>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001640 using transports, protocols, and the
1641 :meth:`loop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +02001642
Yury Selivanov394374e2018-09-17 15:35:24 -04001643 * Another similar :ref:`example <asyncio_example_create_connection-streams>`
Yury Selivanov6758e6e2019-09-29 21:59:55 -07001644 using the high-level :func:`asyncio.open_connection` function
1645 and streams.
Victor Stinner04e6df32014-10-11 16:16:27 +02001646
1647
Yury Selivanov394374e2018-09-17 15:35:24 -04001648.. _asyncio_example_unix_signals:
1649
Victor Stinner04e6df32014-10-11 16:16:27 +02001650Set signal handlers for SIGINT and SIGTERM
Victor Stinnera092a612015-01-09 15:58:41 +01001651^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +02001652
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001653(This ``signals`` example only works on Unix.)
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001654
1655Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`
1656using the :meth:`loop.add_signal_handler` method::
Victor Stinner8b863482014-01-27 10:07:50 +01001657
1658 import asyncio
1659 import functools
1660 import os
1661 import signal
1662
Alexander Vasinceb842e2019-05-03 18:25:36 +03001663 def ask_exit(signame, loop):
Victor Stinner8b863482014-01-27 10:07:50 +01001664 print("got signal %s: exit" % signame)
1665 loop.stop()
1666
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001667 async def main():
1668 loop = asyncio.get_running_loop()
Victor Stinner8b863482014-01-27 10:07:50 +01001669
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001670 for signame in {'SIGINT', 'SIGTERM'}:
1671 loop.add_signal_handler(
1672 getattr(signal, signame),
Alexander Vasinceb842e2019-05-03 18:25:36 +03001673 functools.partial(ask_exit, signame, loop))
Victor Stinner2cef3002014-10-23 22:38:46 +02001674
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001675 await asyncio.sleep(3600)
1676
1677 print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
1678 print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")
1679
1680 asyncio.run(main())