blob: d59cf055b614171132fc4e54e359a380073e4211 [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +01002
Yury Selivanov512d7102018-09-17 19:35:30 -04003
4==========
5Event Loop
6==========
7
8
9.. rubric:: Preface
10
11The event loop is the core of every asyncio application.
12Event loops run asynchronous tasks and callbacks, perform network
13IO operations, and run subprocesses.
14
15Application developers should typically use the high-level asyncio functions,
16such as :func:`asyncio.run`, and should rarely need to reference the loop
17object or call its methods. This section is intended mostly for authors
18of lower-level code, libraries, and frameworks, who need finer control over
19the event loop behavior.
20
21.. rubric:: Obtaining the Event Loop
22
23The following low-level functions can be used to get, set, or create
24an event loop:
25
26.. function:: get_running_loop()
27
28 Return the running event loop in the current OS thread.
29
30 If there is no running event loop a :exc:`RuntimeError` is raised.
31 This function can only be called from a coroutine or a callback.
32
33 .. versionadded:: 3.7
34
35.. function:: get_event_loop()
36
37 Get the current event loop. If there is no current event loop set
38 in the current OS thread and :func:`set_event_loop` has not yet
39 been called, asyncio will create a new event loop and set it as the
40 current one.
41
42 Because this function has rather complex behavior (especially
43 when custom event loop policies are in use), using the
44 :func:`get_running_loop` function is preferred to :func:`get_event_loop`
45 in coroutines and callbacks.
46
47 Consider also using the :func:`asyncio.run` function instead of using
48 lower level functions to manually create and close an event loop.
49
50.. function:: set_event_loop(loop)
51
52 Set *loop* as a current event loop for the current OS thread.
53
54.. function:: new_event_loop()
55
56 Create a new event loop object.
57
58Note that the behaviour of :func:`get_event_loop`, :func:`set_event_loop`,
59and :func:`new_event_loop` functions can be altered by
60:ref:`setting a custom event loop policy <asyncio-policies>`.
61
62
63.. rubric:: Contents
64
65This documentation page contains the following sections:
66
67* The `Event Loop Methods`_ section is the reference documentation of
68 the event loop APIs;
69
70* The `Callback Handles`_ section documents the :class:`Handle` and
71 :class:`TimerHandle` instances which are returned from scheduling
72 methods such as :meth:`loop.call_soon` and :meth:`loop.call_later`;
73
74* The `Server Objects`_ section documents types returned from
75 event loop methods like :meth:`loop.create_server`;
76
77* The `Event Loop Implementations`_ section documents the
78 :class:`SelectorEventLoop` and :class:`ProactorEventLoop` classes;
79
80* The `Examples`_ section showcases how to work with some event
81 loop APIs.
82
83
Victor Stinner9592edb2014-02-02 15:03:02 +010084.. _asyncio-event-loop:
Victor Stinnerea3183f2013-12-03 01:08:00 +010085
Yury Selivanov512d7102018-09-17 19:35:30 -040086Event Loop Methods
87==================
Victor Stinnerea3183f2013-12-03 01:08:00 +010088
Yury Selivanov512d7102018-09-17 19:35:30 -040089Event loops have **low-level** APIs for the following:
lf627d2c82017-07-25 17:03:51 -060090
Yury Selivanov512d7102018-09-17 19:35:30 -040091.. contents::
92 :depth: 1
93 :local:
Victor Stinnerea3183f2013-12-03 01:08:00 +010094
Victor Stinnerea3183f2013-12-03 01:08:00 +010095
Yury Selivanov512d7102018-09-17 19:35:30 -040096Running and stopping the loop
97^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +010098
Yury Selivanov512d7102018-09-17 19:35:30 -040099.. method:: loop.run_until_complete(future)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100100
Yury Selivanov512d7102018-09-17 19:35:30 -0400101 Run until the *future* (an instance of :class:`Future`) has
102 completed.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100103
Yury Selivanov512d7102018-09-17 19:35:30 -0400104 If the argument is a :ref:`coroutine object <coroutine>` it
105 is implicitly scheduled to run as a :class:`asyncio.Task`.
Eli Bendersky136fea22014-02-09 06:55:58 -0800106
Yury Selivanov512d7102018-09-17 19:35:30 -0400107 Return the Future's result or raise its exception.
Guido van Rossumf68afd82016-08-08 09:41:21 -0700108
Yury Selivanov512d7102018-09-17 19:35:30 -0400109.. method:: loop.run_forever()
Guido van Rossumf68afd82016-08-08 09:41:21 -0700110
Yury Selivanov512d7102018-09-17 19:35:30 -0400111 Run the event loop until :meth:`stop` is called.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100112
Yury Selivanov512d7102018-09-17 19:35:30 -0400113 If :meth:`stop` is called before :meth:`run_forever()` is called,
114 the loop will poll the I/O selector once with a timeout of zero,
115 run all callbacks scheduled in response to I/O events (and
116 those that were already scheduled), and then exit.
Victor Stinner83704962015-02-25 14:24:15 +0100117
Guido van Rossum41f69f42015-11-19 13:28:47 -0800118 If :meth:`stop` is called while :meth:`run_forever` is running,
Yury Selivanov512d7102018-09-17 19:35:30 -0400119 the loop will run the current batch of callbacks and then exit.
120 Note that new callbacks scheduled by callbacks will not run in this
121 case; instead, they will run the next time :meth:`run_forever` or
122 :meth:`run_until_complete` is called.
Guido van Rossum41f69f42015-11-19 13:28:47 -0800123
Yury Selivanov512d7102018-09-17 19:35:30 -0400124.. method:: loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100125
Yury Selivanov512d7102018-09-17 19:35:30 -0400126 Stop the event loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100127
Yury Selivanov512d7102018-09-17 19:35:30 -0400128.. method:: loop.is_running()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100129
Yury Selivanov512d7102018-09-17 19:35:30 -0400130 Return ``True`` if the event loop is currently running.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100131
Yury Selivanov512d7102018-09-17 19:35:30 -0400132.. method:: loop.is_closed()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100133
Yury Selivanov512d7102018-09-17 19:35:30 -0400134 Return ``True`` if the event loop was closed.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100135
Yury Selivanov512d7102018-09-17 19:35:30 -0400136.. method:: loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100137
Yury Selivanov512d7102018-09-17 19:35:30 -0400138 Close the event loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100139
Miss Islington (bot)d69f0152018-11-01 14:34:42 -0700140 The loop must not be running when this function is called.
Yury Selivanov512d7102018-09-17 19:35:30 -0400141 Any pending callbacks will be discarded.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100142
Yury Selivanov512d7102018-09-17 19:35:30 -0400143 This method clears all queues and shuts down the executor, but does
144 not wait for the executor to finish.
Guido van Rossum41f69f42015-11-19 13:28:47 -0800145
Yury Selivanov512d7102018-09-17 19:35:30 -0400146 This method is idempotent and irreversible. No other methods
147 should be called after the event loop is closed.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100148
Yury Selivanov512d7102018-09-17 19:35:30 -0400149.. coroutinemethod:: loop.shutdown_asyncgens()
Yury Selivanov03660042016-12-15 17:36:05 -0500150
151 Schedule all currently open :term:`asynchronous generator` objects to
152 close with an :meth:`~agen.aclose()` call. After calling this method,
Yury Selivanov512d7102018-09-17 19:35:30 -0400153 the event loop will issue a warning if a new asynchronous generator
154 is iterated. This should be used to reliably finalize all scheduled
Miss Islington (bot)1f4ea582018-09-17 21:12:05 -0700155 asynchronous generators.
Yury Selivanov512d7102018-09-17 19:35:30 -0400156
Miss Islington (bot)1f4ea582018-09-17 21:12:05 -0700157 Note that there is no need to call this function when
158 :func:`asyncio.run` is used.
159
160 Example::
Yury Selivanov03660042016-12-15 17:36:05 -0500161
162 try:
163 loop.run_forever()
164 finally:
165 loop.run_until_complete(loop.shutdown_asyncgens())
166 loop.close()
167
168 .. versionadded:: 3.6
169
170
Yury Selivanov512d7102018-09-17 19:35:30 -0400171Scheduling callbacks
172^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100173
Yury Selivanov512d7102018-09-17 19:35:30 -0400174.. method:: loop.call_soon(callback, *args, context=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100175
Yury Selivanov512d7102018-09-17 19:35:30 -0400176 Schedule a *callback* to be called with *args* arguments at
177 the next iteration of the event loop.
Victor Stinner8464c242014-11-28 13:15:41 +0100178
Yury Selivanov512d7102018-09-17 19:35:30 -0400179 Callbacks are called in the order in which they are registered.
180 Each callback will be called exactly once.
Victor Stinner8464c242014-11-28 13:15:41 +0100181
Yury Selivanov512d7102018-09-17 19:35:30 -0400182 An optional keyword-only *context* argument allows specifying a
183 custom :class:`contextvars.Context` for the *callback* to run in.
184 The current context is used when no *context* is provided.
Miss Islington (bot)2fc443c2018-05-23 10:59:17 -0700185
Yury Selivanov1096f762015-06-25 13:49:52 -0400186 An instance of :class:`asyncio.Handle` is returned, which can be
Yury Selivanov512d7102018-09-17 19:35:30 -0400187 used later to cancel the callback.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500188
Yury Selivanov512d7102018-09-17 19:35:30 -0400189 This method is not thread-safe.
Victor Stinner8464c242014-11-28 13:15:41 +0100190
Yury Selivanov512d7102018-09-17 19:35:30 -0400191.. method:: loop.call_soon_threadsafe(callback, *args, context=None)
Miss Islington (bot)2fc443c2018-05-23 10:59:17 -0700192
Yury Selivanov512d7102018-09-17 19:35:30 -0400193 A thread-safe variant of :meth:`call_soon`. Must be used to
194 schedule callbacks *from another thread*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100195
Victor Stinner83704962015-02-25 14:24:15 +0100196 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
197 section of the documentation.
198
Yury Selivanov512d7102018-09-17 19:35:30 -0400199.. versionchanged:: 3.7
200 The *context* keyword-only parameter was added. See :pep:`567`
201 for more details.
202
203.. _asyncio-pass-keywords:
204
205.. note::
206
207 Most :mod:`asyncio` scheduling functions don't allow passing
208 keyword arguments. To do that, use :func:`functools.partial`::
209
210 # will schedule "print("Hello", flush=True)"
211 loop.call_soon(
212 functools.partial(print, "Hello", flush=True))
213
214 Using partial objects is usually more convenient than using lambdas,
215 as asyncio can render partial objects better in debug and error
216 messages.
Miss Islington (bot)2fc443c2018-05-23 10:59:17 -0700217
Victor Stinnerea3183f2013-12-03 01:08:00 +0100218
Victor Stinner45b27ed2014-02-01 02:36:43 +0100219.. _asyncio-delayed-calls:
220
Yury Selivanov512d7102018-09-17 19:35:30 -0400221Scheduling delayed callbacks
222^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100223
Yury Selivanov512d7102018-09-17 19:35:30 -0400224Event loop provides mechanisms to schedule callback functions
225to be called at some point in the future. Event loop uses monotonic
226clocks to track time.
Victor Stinnerfd9d3742014-02-18 09:37:43 +0100227
Victor Stinner45b27ed2014-02-01 02:36:43 +0100228
Yury Selivanov512d7102018-09-17 19:35:30 -0400229.. method:: loop.call_later(delay, callback, *args, context=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100230
Yury Selivanov512d7102018-09-17 19:35:30 -0400231 Schedule *callback* to be called after the given *delay*
232 number of seconds (can be either an int or a float).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100233
Yury Selivanov512d7102018-09-17 19:35:30 -0400234 An instance of :class:`asyncio.TimerHandle` is returned which can
235 be used to cancel the callback.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100236
Yury Selivanov512d7102018-09-17 19:35:30 -0400237 *callback* will be called exactly once. If two callbacks are
238 scheduled for exactly the same time, the order in which they
239 are called is undefined.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100240
Yury Selivanov512d7102018-09-17 19:35:30 -0400241 The optional positional *args* will be passed to the callback when
242 it is called. If you want the callback to be called with keyword
243 arguments use :func:`functools.partial`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100244
Yury Selivanov512d7102018-09-17 19:35:30 -0400245 An optional keyword-only *context* argument allows specifying a
246 custom :class:`contextvars.Context` for the *callback* to run in.
247 The current context is used when no *context* is provided.
Victor Stinner8464c242014-11-28 13:15:41 +0100248
Miss Islington (bot)2fc443c2018-05-23 10:59:17 -0700249 .. versionchanged:: 3.7
250 The *context* keyword-only parameter was added. See :pep:`567`
251 for more details.
252
Yury Selivanov512d7102018-09-17 19:35:30 -0400253 .. versionchanged:: 3.7.1
254 In Python 3.7.0 and earlier with the default event loop implementation,
255 the *delay* could not exceed one day.
256 This has been fixed in Python 3.7.1.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100257
Yury Selivanov512d7102018-09-17 19:35:30 -0400258.. method:: loop.call_at(when, callback, *args, context=None)
259
260 Schedule *callback* to be called at the given absolute timestamp
261 *when* (an int or a float), using the same time reference as
262 :meth:`loop.time`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100263
264 This method's behavior is the same as :meth:`call_later`.
265
Yury Selivanov512d7102018-09-17 19:35:30 -0400266 An instance of :class:`asyncio.TimerHandle` is returned which can
267 be used to cancel the callback.
Victor Stinner8464c242014-11-28 13:15:41 +0100268
Miss Islington (bot)2fc443c2018-05-23 10:59:17 -0700269 .. versionchanged:: 3.7
270 The *context* keyword-only parameter was added. See :pep:`567`
271 for more details.
272
Yury Selivanov512d7102018-09-17 19:35:30 -0400273 .. versionchanged:: 3.7.1
274 In Python 3.7.0 and earlier with the default event loop implementation,
275 the difference between *when* and the current time could not exceed
276 one day. This has been fixed in Python 3.7.1.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100277
Yury Selivanov512d7102018-09-17 19:35:30 -0400278.. method:: loop.time()
279
280 Return the current time, as a :class:`float` value, according to
281 the event loop's internal monotonic clock.
282
283.. note::
284
285 Timeouts (relative *delay* or absolute *when*) should not
286 exceed one day.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100287
Victor Stinner3e09e322013-12-03 01:22:06 +0100288.. seealso::
289
290 The :func:`asyncio.sleep` function.
291
Victor Stinnerea3183f2013-12-03 01:08:00 +0100292
Yury Selivanov512d7102018-09-17 19:35:30 -0400293Creating Futures and Tasks
294^^^^^^^^^^^^^^^^^^^^^^^^^^
Yury Selivanov950204d2016-05-16 16:23:00 -0400295
Yury Selivanov512d7102018-09-17 19:35:30 -0400296.. method:: loop.create_future()
Yury Selivanov950204d2016-05-16 16:23:00 -0400297
Yury Selivanov512d7102018-09-17 19:35:30 -0400298 Create an :class:`asyncio.Future` object attached to the event loop.
Yury Selivanov950204d2016-05-16 16:23:00 -0400299
Yury Selivanov512d7102018-09-17 19:35:30 -0400300 This is the preferred way to create Futures in asyncio. This lets
301 third-party event loops provide alternative implementations of
302 the Future object (with better performance or instrumentation).
Yury Selivanov950204d2016-05-16 16:23:00 -0400303
304 .. versionadded:: 3.5.2
305
Yury Selivanov512d7102018-09-17 19:35:30 -0400306.. method:: loop.create_task(coro)
Yury Selivanov950204d2016-05-16 16:23:00 -0400307
Yury Selivanov512d7102018-09-17 19:35:30 -0400308 Schedule the execution of a :ref:`coroutine`.
309 Return a :class:`Task` object.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200310
Yury Selivanov512d7102018-09-17 19:35:30 -0400311 Third-party event loops can use their own subclass of :class:`Task`
312 for interoperability. In this case, the result type is a subclass
313 of :class:`Task`.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200314
Yury Selivanov512d7102018-09-17 19:35:30 -0400315.. method:: loop.set_task_factory(factory)
Yury Selivanov71854612015-05-11 16:28:27 -0400316
317 Set a task factory that will be used by
Yury Selivanov512d7102018-09-17 19:35:30 -0400318 :meth:`loop.create_task`.
Yury Selivanov71854612015-05-11 16:28:27 -0400319
320 If *factory* is ``None`` the default task factory will be set.
Yury Selivanov512d7102018-09-17 19:35:30 -0400321 Otherwise, *factory* must be a *callable* with the signature matching
322 ``(loop, coro)``, where *loop* is a reference to the active
323 event loop, and *coro* is a coroutine object. The callable
324 must return a :class:`asyncio.Future`-compatible object.
Yury Selivanov71854612015-05-11 16:28:27 -0400325
Yury Selivanov512d7102018-09-17 19:35:30 -0400326.. method:: loop.get_task_factory()
Yury Selivanov71854612015-05-11 16:28:27 -0400327
Yury Selivanov512d7102018-09-17 19:35:30 -0400328 Return a task factory or ``None`` if the default one is in use.
Yury Selivanov71854612015-05-11 16:28:27 -0400329
Victor Stinner530ef2f2014-07-08 12:39:10 +0200330
Yury Selivanov512d7102018-09-17 19:35:30 -0400331Opening network connections
332^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100333
Yury Selivanov512d7102018-09-17 19:35:30 -0400334.. coroutinemethod:: loop.create_connection(protocol_factory, \
335 host=None, port=None, \*, ssl=None, \
336 family=0, proto=0, flags=0, sock=None, \
337 local_addr=None, server_hostname=None, \
338 ssl_handshake_timeout=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100339
Yury Selivanov512d7102018-09-17 19:35:30 -0400340 Open a streaming transport connection to a given
341 address specified by *host* and *port*.
342
343 The socket family can be either :py:data:`~socket.AF_INET` or
344 :py:data:`~socket.AF_INET6` depending on *host* (or the *family*
345 argument, if provided).
346
347 The socket type will be :py:data:`~socket.SOCK_STREAM`.
348
349 *protocol_factory* must be a callable returning an
350 :ref:`asyncio protocol <asyncio-protocol>` implementation.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100351
Yury Selivanov19a44f62017-12-14 20:53:26 -0500352 This method will try to establish the connection in the background.
353 When successful, it returns a ``(transport, protocol)`` pair.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100354
355 The chronological synopsis of the underlying operation is as follows:
356
Yury Selivanov512d7102018-09-17 19:35:30 -0400357 #. The connection is established and a :ref:`transport <asyncio-transport>`
358 is created for it.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100359
Yury Selivanov512d7102018-09-17 19:35:30 -0400360 #. *protocol_factory* is called without arguments and is expected to
361 return a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100362
Yury Selivanov512d7102018-09-17 19:35:30 -0400363 #. The protocol instance is coupled with the transport by calling its
364 :meth:`~BaseProtocol.connection_made` method.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100365
Yury Selivanov512d7102018-09-17 19:35:30 -0400366 #. A ``(transport, protocol)`` tuple is returned on success.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100367
Yury Selivanov512d7102018-09-17 19:35:30 -0400368 The created transport is an implementation-dependent bidirectional
369 stream.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100370
Yury Selivanov512d7102018-09-17 19:35:30 -0400371 Other arguments:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100372
373 * *ssl*: if given and not false, a SSL/TLS transport is created
374 (by default a plain TCP transport is created). If *ssl* is
375 a :class:`ssl.SSLContext` object, this context is used to create
Yury Selivanov512d7102018-09-17 19:35:30 -0400376 the transport; if *ssl* is :const:`True`, a default context returned
377 from :func:`ssl.create_default_context` is used.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100378
Berker Peksag9c1dba22014-09-28 00:00:58 +0300379 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100380
Yury Selivanov512d7102018-09-17 19:35:30 -0400381 * *server_hostname* sets or overrides the hostname that the target
382 server's certificate will be matched against. Should only be passed
383 if *ssl* is not ``None``. By default the value of the *host* argument
Victor Stinnerea3183f2013-12-03 01:08:00 +0100384 is used. If *host* is empty, there is no default and you must pass a
385 value for *server_hostname*. If *server_hostname* is an empty
386 string, hostname matching is disabled (which is a serious security
Yury Selivanov512d7102018-09-17 19:35:30 -0400387 risk, allowing for potential man-in-the-middle attacks).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100388
389 * *family*, *proto*, *flags* are the optional address family, protocol
390 and flags to be passed through to getaddrinfo() for *host* resolution.
391 If given, these should all be integers from the corresponding
392 :mod:`socket` module constants.
393
394 * *sock*, if given, should be an existing, already connected
395 :class:`socket.socket` object to be used by the transport.
396 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
397 and *local_addr* should be specified.
398
399 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
400 to bind the socket to locally. The *local_host* and *local_port*
Yury Selivanov512d7102018-09-17 19:35:30 -0400401 are looked up using ``getaddrinfo()``, similarly to *host* and *port*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100402
Yury Selivanov512d7102018-09-17 19:35:30 -0400403 * *ssl_handshake_timeout* is (for a TLS connection) the time in seconds
404 to wait for the TLS handshake to complete before aborting the connection.
Miss Islington (bot)87936d02018-06-04 09:05:46 -0700405 ``60.0`` seconds if ``None`` (default).
Neil Aspinallf7686c12017-12-19 19:45:42 +0000406
407 .. versionadded:: 3.7
408
409 The *ssl_handshake_timeout* parameter.
410
Yury Selivanov512d7102018-09-17 19:35:30 -0400411 .. versionchanged:: 3.6
412
413 The socket option :py:data:`~socket.TCP_NODELAY` is set by default
414 for all TCP connections.
415
Victor Stinner60208a12015-09-15 22:41:52 +0200416 .. versionchanged:: 3.5
417
Yury Selivanov512d7102018-09-17 19:35:30 -0400418 Added support for SSL/TLS in :class:`ProactorEventLoop`.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200419
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100420 .. seealso::
421
Yury Selivanov512d7102018-09-17 19:35:30 -0400422 The :func:`open_connection` function is a high-level alternative
423 API. It returns a pair of (:class:`StreamReader`, :class:`StreamWriter`)
424 that can be used directly in async/await code.
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100425
Yury Selivanov512d7102018-09-17 19:35:30 -0400426.. coroutinemethod:: loop.create_datagram_endpoint(protocol_factory, \
427 local_addr=None, remote_addr=None, \*, \
428 family=0, proto=0, flags=0, \
429 reuse_address=None, reuse_port=None, \
430 allow_broadcast=None, sock=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100431
Yury Selivanov512d7102018-09-17 19:35:30 -0400432 Create a datagram connection.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100433
Yury Selivanov512d7102018-09-17 19:35:30 -0400434 The socket family can be either :py:data:`~socket.AF_INET`,
435 :py:data:`~socket.AF_INET6`, or :py:data:`~socket.AF_UNIX`,
436 depending on *host* (or the *family* argument, if provided).
Victor Stinnera6919aa2014-02-19 13:32:34 +0100437
Yury Selivanov512d7102018-09-17 19:35:30 -0400438 The socket type will be :py:data:`~socket.SOCK_DGRAM`.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100439
Yury Selivanov512d7102018-09-17 19:35:30 -0400440 *protocol_factory* must be a callable returning a
441 :ref:`protocol <asyncio-protocol>` implementation.
442
443 A tuple of ``(transport, protocol)`` is returned on success.
444
445 Other arguments:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700446
447 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
448 to bind the socket to locally. The *local_host* and *local_port*
449 are looked up using :meth:`getaddrinfo`.
450
451 * *remote_addr*, if given, is a ``(remote_host, remote_port)`` tuple used
452 to connect the socket to a remote address. The *remote_host* and
453 *remote_port* are looked up using :meth:`getaddrinfo`.
454
455 * *family*, *proto*, *flags* are the optional address family, protocol
456 and flags to be passed through to :meth:`getaddrinfo` for *host*
457 resolution. If given, these should all be integers from the
458 corresponding :mod:`socket` module constants.
459
460 * *reuse_address* tells the kernel to reuse a local socket in
Yury Selivanov512d7102018-09-17 19:35:30 -0400461 ``TIME_WAIT`` state, without waiting for its natural timeout to
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300462 expire. If not specified will automatically be set to ``True`` on
Yury Selivanov512d7102018-09-17 19:35:30 -0400463 Unix.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700464
465 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
466 same port as other existing endpoints are bound to, so long as they all
467 set this flag when being created. This option is not supported on Windows
Yury Selivanov512d7102018-09-17 19:35:30 -0400468 and some Unixes. If the :py:data:`~socket.SO_REUSEPORT` constant is not
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700469 defined then this capability is unsupported.
470
471 * *allow_broadcast* tells the kernel to allow this endpoint to send
472 messages to the broadcast address.
473
474 * *sock* can optionally be specified in order to use a preexisting,
475 already connected, :class:`socket.socket` object to be used by the
476 transport. If specified, *local_addr* and *remote_addr* should be omitted
477 (must be :const:`None`).
Victor Stinnera6919aa2014-02-19 13:32:34 +0100478
Yury Selivanov512d7102018-09-17 19:35:30 -0400479 On Windows, with :class:`ProactorEventLoop`, this method is not supported.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200480
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200481 See :ref:`UDP echo client protocol <asyncio-udp-echo-client-protocol>` and
482 :ref:`UDP echo server protocol <asyncio-udp-echo-server-protocol>` examples.
483
Miss Islington (bot)c6348cf2018-05-14 13:12:38 -0700484 .. versionchanged:: 3.4.4
485 The *family*, *proto*, *flags*, *reuse_address*, *reuse_port,
486 *allow_broadcast*, and *sock* parameters were added.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100487
Yury Selivanov512d7102018-09-17 19:35:30 -0400488.. coroutinemethod:: loop.create_unix_connection(protocol_factory, \
489 path=None, \*, ssl=None, sock=None, \
490 server_hostname=None, ssl_handshake_timeout=None)
Victor Stinnera6919aa2014-02-19 13:32:34 +0100491
Yury Selivanov512d7102018-09-17 19:35:30 -0400492 Create a Unix connection.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100493
Yury Selivanov512d7102018-09-17 19:35:30 -0400494 The socket family will be :py:data:`~socket.AF_UNIX`; socket
495 type will be :py:data:`~socket.SOCK_STREAM`.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100496
Yury Selivanov512d7102018-09-17 19:35:30 -0400497 A tuple of ``(transport, protocol)`` is returned on success.
Guido van Rossum9e80eeb2016-11-03 14:17:25 -0700498
Yury Selivanov512d7102018-09-17 19:35:30 -0400499 *path* is the name of a Unix domain socket and is required,
500 unless a *sock* parameter is specified. Abstract Unix sockets,
501 :class:`str`, :class:`bytes`, and :class:`~pathlib.Path` paths are
502 supported.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100503
Yury Selivanov512d7102018-09-17 19:35:30 -0400504 See the documentation of the :meth:`loop.create_connection` method
505 for information about arguments to this method.
506
Cheryl Sabellab248a8c2018-10-15 16:52:26 -0400507 .. availability:: Unix.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100508
Neil Aspinallf7686c12017-12-19 19:45:42 +0000509 .. versionadded:: 3.7
510
511 The *ssl_handshake_timeout* parameter.
512
Yury Selivanov423fd362017-11-20 17:26:28 -0500513 .. versionchanged:: 3.7
514
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -0700515 The *path* parameter can now be a :term:`path-like object`.
Yury Selivanov423fd362017-11-20 17:26:28 -0500516
Victor Stinnera6919aa2014-02-19 13:32:34 +0100517
Yury Selivanov512d7102018-09-17 19:35:30 -0400518Creating network servers
519^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100520
Yury Selivanov512d7102018-09-17 19:35:30 -0400521.. coroutinemethod:: loop.create_server(protocol_factory, \
522 host=None, port=None, \*, \
523 family=socket.AF_UNSPEC, \
524 flags=socket.AI_PASSIVE, \
525 sock=None, backlog=100, ssl=None, \
526 reuse_address=None, reuse_port=None, \
527 ssl_handshake_timeout=None, start_serving=True)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100528
Yury Selivanov512d7102018-09-17 19:35:30 -0400529 Create a TCP server (socket type :data:`~socket.SOCK_STREAM`) listening
530 on *port* of the *host* address.
Victor Stinner33f6abe2014-10-12 20:36:04 +0200531
Yury Selivanov512d7102018-09-17 19:35:30 -0400532 Returns a :class:`Server` object.
Victor Stinner33f6abe2014-10-12 20:36:04 +0200533
Yury Selivanov512d7102018-09-17 19:35:30 -0400534 Arguments:
Victor Stinner33f6abe2014-10-12 20:36:04 +0200535
Yury Selivanov512d7102018-09-17 19:35:30 -0400536 * *protocol_factory* must be a callable returning a
537 :ref:`protocol <asyncio-protocol>` implementation.
538
539 * The *host* parameter can be set to several types which determine where
540 the server would be listening:
541
542 - If *host* is a string, the TCP server is bound to a single network
543 interface specified by *host*.
544
545 - If *host* is a sequence of strings, the TCP server is bound to all
546 network interfaces specified by the sequence.
547
548 - If *host* is an empty string or ``None``, all interfaces are
549 assumed and a list of multiple sockets will be returned (most likely
550 one for IPv4 and another one for IPv6).
Victor Stinner33f6abe2014-10-12 20:36:04 +0200551
552 * *family* can be set to either :data:`socket.AF_INET` or
Yury Selivanov512d7102018-09-17 19:35:30 -0400553 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6.
554 If not set, the *family* will be determined from host name
555 (defaults to :data:`~socket.AF_UNSPEC`).
Victor Stinner33f6abe2014-10-12 20:36:04 +0200556
557 * *flags* is a bitmask for :meth:`getaddrinfo`.
558
559 * *sock* can optionally be specified in order to use a preexisting
Yury Selivanov512d7102018-09-17 19:35:30 -0400560 socket object. If specified, *host* and *port* must not be specified.
Victor Stinner33f6abe2014-10-12 20:36:04 +0200561
562 * *backlog* is the maximum number of queued connections passed to
563 :meth:`~socket.socket.listen` (defaults to 100).
564
Yury Selivanov512d7102018-09-17 19:35:30 -0400565 * *ssl* can be set to an :class:`~ssl.SSLContext` instance to enable
566 TLS over the accepted connections.
Victor Stinner33f6abe2014-10-12 20:36:04 +0200567
568 * *reuse_address* tells the kernel to reuse a local socket in
Yury Selivanov512d7102018-09-17 19:35:30 -0400569 ``TIME_WAIT`` state, without waiting for its natural timeout to
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300570 expire. If not specified will automatically be set to ``True`` on
Yury Selivanov512d7102018-09-17 19:35:30 -0400571 Unix.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100572
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700573 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
574 same port as other existing endpoints are bound to, so long as they all
575 set this flag when being created. This option is not supported on
576 Windows.
577
Yury Selivanov512d7102018-09-17 19:35:30 -0400578 * *ssl_handshake_timeout* is (for a TLS server) the time in seconds to wait
579 for the TLS handshake to complete before aborting the connection.
Miss Islington (bot)87936d02018-06-04 09:05:46 -0700580 ``60.0`` seconds if ``None`` (default).
Neil Aspinallf7686c12017-12-19 19:45:42 +0000581
Yury Selivanovc9070d02018-01-25 18:08:09 -0500582 * *start_serving* set to ``True`` (the default) causes the created server
583 to start accepting connections immediately. When set to ``False``,
584 the user should await on :meth:`Server.start_serving` or
585 :meth:`Server.serve_forever` to make the server to start accepting
586 connections.
587
Neil Aspinallf7686c12017-12-19 19:45:42 +0000588 .. versionadded:: 3.7
589
Yury Selivanov512d7102018-09-17 19:35:30 -0400590 Added *ssl_handshake_timeout* and *start_serving* parameters.
591
592 .. versionchanged:: 3.6
593
594 The socket option :py:data:`~socket.TCP_NODELAY` is set by default
595 for all TCP connections.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000596
Victor Stinner60208a12015-09-15 22:41:52 +0200597 .. versionchanged:: 3.5
598
Yury Selivanov512d7102018-09-17 19:35:30 -0400599 Added support for SSL/TLS in :class:`ProactorEventLoop`.
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100600
Victor Stinner7b58a2b2015-09-21 18:41:05 +0200601 .. versionchanged:: 3.5.1
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200602
Yury Selivanov512d7102018-09-17 19:35:30 -0400603 The *host* parameter can be a sequence of strings.
604
605 .. seealso::
606
607 The :func:`start_server` function is a higher-level alternative API
608 that returns a pair of :class:`StreamReader` and :class:`StreamWriter`
609 that can be used in an async/await code.
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200610
Victor Stinnerea3183f2013-12-03 01:08:00 +0100611
Yury Selivanov512d7102018-09-17 19:35:30 -0400612.. coroutinemethod:: loop.create_unix_server(protocol_factory, path=None, \
613 \*, sock=None, backlog=100, ssl=None, \
614 ssl_handshake_timeout=None, start_serving=True)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100615
Yury Selivanov512d7102018-09-17 19:35:30 -0400616 Similar to :meth:`loop.create_server` but works with the
617 :py:data:`~socket.AF_UNIX` socket family.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100618
Yury Selivanov512d7102018-09-17 19:35:30 -0400619 *path* is the name of a Unix domain socket, and is required,
620 unless a *sock* argument is provided. Abstract Unix sockets,
621 :class:`str`, :class:`bytes`, and :class:`~pathlib.Path` paths
622 are supported.
Yury Selivanov423fd362017-11-20 17:26:28 -0500623
Yury Selivanov512d7102018-09-17 19:35:30 -0400624 See the documentation of the :meth:`loop.create_server` method
625 for information about arguments to this method.
626
Cheryl Sabellab248a8c2018-10-15 16:52:26 -0400627 .. availability:: Unix.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100628
Neil Aspinallf7686c12017-12-19 19:45:42 +0000629 .. versionadded:: 3.7
630
Miss Islington (bot)f4dcf492018-06-08 08:54:31 -0700631 The *ssl_handshake_timeout* and *start_serving* parameters.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000632
Yury Selivanov423fd362017-11-20 17:26:28 -0500633 .. versionchanged:: 3.7
634
635 The *path* parameter can now be a :class:`~pathlib.Path` object.
636
Yury Selivanov512d7102018-09-17 19:35:30 -0400637.. coroutinemethod:: loop.connect_accepted_socket(protocol_factory, \
638 sock, \*, ssl=None, ssl_handshake_timeout=None)
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500639
Yury Selivanov512d7102018-09-17 19:35:30 -0400640 Wrap an already accepted connection into a transport/protocol pair.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500641
Yury Selivanov512d7102018-09-17 19:35:30 -0400642 This method can be used by servers that accept connections outside
643 of asyncio but that use asyncio to handle them.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500644
645 Parameters:
646
Yury Selivanov512d7102018-09-17 19:35:30 -0400647 * *protocol_factory* must be a callable returning a
648 :ref:`protocol <asyncio-protocol>` implementation.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500649
Yury Selivanov512d7102018-09-17 19:35:30 -0400650 * *sock* is a preexisting socket object returned from
651 :meth:`socket.accept <socket.socket.accept>`.
652
653 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over
654 the accepted connections.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500655
Neil Aspinallf7686c12017-12-19 19:45:42 +0000656 * *ssl_handshake_timeout* is (for an SSL connection) the time in seconds to
657 wait for the SSL handshake to complete before aborting the connection.
Miss Islington (bot)87936d02018-06-04 09:05:46 -0700658 ``60.0`` seconds if ``None`` (default).
Neil Aspinallf7686c12017-12-19 19:45:42 +0000659
Yury Selivanov512d7102018-09-17 19:35:30 -0400660 Returns a ``(transport, protocol)`` pair.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100661
Neil Aspinallf7686c12017-12-19 19:45:42 +0000662 .. versionadded:: 3.7
663
664 The *ssl_handshake_timeout* parameter.
665
AraHaan431665b2017-11-21 11:06:26 -0500666 .. versionadded:: 3.5.3
667
668
Yury Selivanov512d7102018-09-17 19:35:30 -0400669Transferring files
670^^^^^^^^^^^^^^^^^^
Andrew Svetlov7c684072018-01-27 21:22:47 +0200671
Yury Selivanov512d7102018-09-17 19:35:30 -0400672.. coroutinemethod:: loop.sendfile(transport, file, \
673 offset=0, count=None, *, fallback=True)
Andrew Svetlov7c684072018-01-27 21:22:47 +0200674
Yury Selivanov512d7102018-09-17 19:35:30 -0400675 Send a *file* over a *transport*. Return the total number of bytes
676 sent.
Andrew Svetlov7c684072018-01-27 21:22:47 +0200677
678 The method uses high-performance :meth:`os.sendfile` if available.
679
680 *file* must be a regular file object opened in binary mode.
681
682 *offset* tells from where to start reading the file. If specified,
683 *count* is the total number of bytes to transmit as opposed to
Yury Selivanov512d7102018-09-17 19:35:30 -0400684 sending the file until EOF is reached. File position is always updated,
685 even when this method raises an error, and
686 :meth:`file.tell() <io.IOBase.tell>` can be used to obtain the actual
687 number of bytes sent.
Andrew Svetlov7c684072018-01-27 21:22:47 +0200688
689 *fallback* set to ``True`` makes asyncio to manually read and send
Yury Selivanov512d7102018-09-17 19:35:30 -0400690 the file when the platform does not support the sendfile system call
Andrew Svetlov7c684072018-01-27 21:22:47 +0200691 (e.g. Windows or SSL socket on Unix).
692
693 Raise :exc:`SendfileNotAvailableError` if the system does not support
Yury Selivanov512d7102018-09-17 19:35:30 -0400694 the *sendfile* syscall and *fallback* is ``False``.
Andrew Svetlov7c684072018-01-27 21:22:47 +0200695
696 .. versionadded:: 3.7
697
698
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500699TLS Upgrade
Yury Selivanov512d7102018-09-17 19:35:30 -0400700^^^^^^^^^^^
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500701
Yury Selivanov512d7102018-09-17 19:35:30 -0400702.. coroutinemethod:: loop.start_tls(transport, protocol, \
703 sslcontext, \*, server_side=False, \
704 server_hostname=None, ssl_handshake_timeout=None)
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500705
Yury Selivanov512d7102018-09-17 19:35:30 -0400706 Upgrade an existing transport-based connection to TLS.
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500707
Yury Selivanov512d7102018-09-17 19:35:30 -0400708 Return a new transport instance, that the *protocol* must start using
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500709 immediately after the *await*. The *transport* instance passed to
710 the *start_tls* method should never be used again.
711
712 Parameters:
713
714 * *transport* and *protocol* instances that methods like
Yury Selivanov512d7102018-09-17 19:35:30 -0400715 :meth:`~loop.create_server` and
716 :meth:`~loop.create_connection` return.
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500717
718 * *sslcontext*: a configured instance of :class:`~ssl.SSLContext`.
719
720 * *server_side* pass ``True`` when a server-side connection is being
Yury Selivanov512d7102018-09-17 19:35:30 -0400721 upgraded (like the one created by :meth:`~loop.create_server`).
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500722
723 * *server_hostname*: sets or overrides the host name that the target
724 server's certificate will be matched against.
725
Yury Selivanov512d7102018-09-17 19:35:30 -0400726 * *ssl_handshake_timeout* is (for a TLS connection) the time in seconds to
727 wait for the TLS handshake to complete before aborting the connection.
Miss Islington (bot)87936d02018-06-04 09:05:46 -0700728 ``60.0`` seconds if ``None`` (default).
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500729
730 .. versionadded:: 3.7
731
732
Yury Selivanov512d7102018-09-17 19:35:30 -0400733Watching file descriptors
734^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerc1567df2014-02-08 23:22:58 +0100735
Yury Selivanov512d7102018-09-17 19:35:30 -0400736.. method:: loop.add_reader(fd, callback, \*args)
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200737
Yury Selivanov512d7102018-09-17 19:35:30 -0400738 Start monitoring the *fd* file descriptor for read availability and
739 invoke *callback* with the specified arguments once *fd* is available for
740 reading.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200741
Yury Selivanov512d7102018-09-17 19:35:30 -0400742.. method:: loop.remove_reader(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100743
Yury Selivanov512d7102018-09-17 19:35:30 -0400744 Stop monitoring the *fd* file descriptor for read availability.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100745
Yury Selivanov512d7102018-09-17 19:35:30 -0400746.. method:: loop.add_writer(fd, callback, \*args)
Victor Stinner8464c242014-11-28 13:15:41 +0100747
Yury Selivanov512d7102018-09-17 19:35:30 -0400748 Start monitoring the *fd* file descriptor for write availability and
749 invoke *callback* with the specified arguments once *fd* is available for
750 writing.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100751
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700752 Use :func:`functools.partial` :ref:`to pass keyword arguments
Miss Islington (bot)6627d3a2018-12-03 23:36:31 -0800753 <asyncio-pass-keywords>` to *callback*.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100754
Yury Selivanov512d7102018-09-17 19:35:30 -0400755.. method:: loop.remove_writer(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100756
Yury Selivanov512d7102018-09-17 19:35:30 -0400757 Stop monitoring the *fd* file descriptor for write availability.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100758
Yury Selivanov512d7102018-09-17 19:35:30 -0400759See also :ref:`Platform Support <asyncio-platform-support>` section
760for some limitations of these methods.
Victor Stinner04e6df32014-10-11 16:16:27 +0200761
Victor Stinnerc1567df2014-02-08 23:22:58 +0100762
Yury Selivanov512d7102018-09-17 19:35:30 -0400763Working with socket objects directly
764^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerc1567df2014-02-08 23:22:58 +0100765
Yury Selivanov512d7102018-09-17 19:35:30 -0400766In general, protocol implementations that use transport-based APIs
767such as :meth:`loop.create_connection` and :meth:`loop.create_server`
768are faster than implementations that work with sockets directly.
769However, there are some use cases when performance is not critical, and
770working with :class:`~socket.socket` objects directly is more
771convenient.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100772
Yury Selivanov512d7102018-09-17 19:35:30 -0400773.. coroutinemethod:: loop.sock_recv(sock, nbytes)
Yury Selivanov55c50842016-06-08 12:48:15 -0400774
Yury Selivanov512d7102018-09-17 19:35:30 -0400775 Receive up to *nbytes* from *sock*. Asynchronous version of
776 :meth:`socket.recv() <socket.socket.recv>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100777
Yury Selivanov512d7102018-09-17 19:35:30 -0400778 Return the received data as a bytes object.
779
780 *sock* must be a non-blocking socket.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200781
Yury Selivanov19a44f62017-12-14 20:53:26 -0500782 .. versionchanged:: 3.7
Yury Selivanov512d7102018-09-17 19:35:30 -0400783 Even though this method was always documented as a coroutine
784 method, releases before Python 3.7 returned a :class:`Future`.
785 Since Python 3.7 this is an ``async def`` method.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100786
Yury Selivanov512d7102018-09-17 19:35:30 -0400787.. coroutinemethod:: loop.sock_recv_into(sock, buf)
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200788
Yury Selivanov512d7102018-09-17 19:35:30 -0400789 Receive data from *sock* into the *buf* buffer. Modeled after the blocking
790 :meth:`socket.recv_into() <socket.socket.recv_into>` method.
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200791
Yury Selivanov512d7102018-09-17 19:35:30 -0400792 Return the number of bytes written to the buffer.
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200793
Yury Selivanov512d7102018-09-17 19:35:30 -0400794 *sock* must be a non-blocking socket.
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200795
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200796 .. versionadded:: 3.7
797
Yury Selivanov512d7102018-09-17 19:35:30 -0400798.. coroutinemethod:: loop.sock_sendall(sock, data)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100799
Yury Selivanov512d7102018-09-17 19:35:30 -0400800 Send *data* to the *sock* socket. Asynchronous version of
801 :meth:`socket.sendall() <socket.socket.sendall>`.
Yury Selivanov55c50842016-06-08 12:48:15 -0400802
Yury Selivanov512d7102018-09-17 19:35:30 -0400803 This method continues to send to the socket until either all data
804 in *data* has been sent or an error occurs. ``None`` is returned
805 on success. On error, an exception is raised. Additionally, there is no way
806 to determine how much data, if any, was successfully processed by the
807 receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100808
Yury Selivanov512d7102018-09-17 19:35:30 -0400809 *sock* must be a non-blocking socket.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200810
Yury Selivanov19a44f62017-12-14 20:53:26 -0500811 .. versionchanged:: 3.7
812 Even though the method was always documented as a coroutine
813 method, before Python 3.7 it returned an :class:`Future`.
814 Since Python 3.7, this is an ``async def`` method.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100815
Yury Selivanov512d7102018-09-17 19:35:30 -0400816.. coroutinemethod:: loop.sock_connect(sock, address)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100817
Yury Selivanov512d7102018-09-17 19:35:30 -0400818 Connect *sock* to a remote socket at *address*.
Victor Stinner1b0580b2014-02-13 09:24:37 +0100819
Yury Selivanov512d7102018-09-17 19:35:30 -0400820 Asynchronous version of :meth:`socket.connect() <socket.socket.connect>`.
821
822 *sock* must be a non-blocking socket.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200823
Yury Selivanov55c50842016-06-08 12:48:15 -0400824 .. versionchanged:: 3.5.2
825 ``address`` no longer needs to be resolved. ``sock_connect``
826 will try to check if the *address* is already resolved by calling
827 :func:`socket.inet_pton`. If not,
Yury Selivanov512d7102018-09-17 19:35:30 -0400828 :meth:`loop.getaddrinfo` will be used to resolve the
Yury Selivanov55c50842016-06-08 12:48:15 -0400829 *address*.
830
Victor Stinnerc1567df2014-02-08 23:22:58 +0100831 .. seealso::
832
Yury Selivanov512d7102018-09-17 19:35:30 -0400833 :meth:`loop.create_connection`
Yury Selivanov55c50842016-06-08 12:48:15 -0400834 and :func:`asyncio.open_connection() <open_connection>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100835
836
Yury Selivanov512d7102018-09-17 19:35:30 -0400837.. coroutinemethod:: loop.sock_accept(sock)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100838
Yury Selivanov512d7102018-09-17 19:35:30 -0400839 Accept a connection. Modeled after the blocking
840 :meth:`socket.accept() <socket.socket.accept>` method.
Yury Selivanov55c50842016-06-08 12:48:15 -0400841
842 The socket must be bound to an address and listening
Victor Stinnerc1567df2014-02-08 23:22:58 +0100843 for connections. The return value is a pair ``(conn, address)`` where *conn*
844 is a *new* socket object usable to send and receive data on the connection,
845 and *address* is the address bound to the socket on the other end of the
846 connection.
847
Yury Selivanov512d7102018-09-17 19:35:30 -0400848 *sock* must be a non-blocking socket.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200849
Yury Selivanov19a44f62017-12-14 20:53:26 -0500850 .. versionchanged:: 3.7
851 Even though the method was always documented as a coroutine
852 method, before Python 3.7 it returned a :class:`Future`.
853 Since Python 3.7, this is an ``async def`` method.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100854
855 .. seealso::
856
Yury Selivanov512d7102018-09-17 19:35:30 -0400857 :meth:`loop.create_server` and :func:`start_server`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100858
Yury Selivanov512d7102018-09-17 19:35:30 -0400859.. coroutinemethod:: loop.sock_sendfile(sock, file, offset=0, count=None, \
860 \*, fallback=True)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200861
Yury Selivanov512d7102018-09-17 19:35:30 -0400862 Send a file using high-performance :mod:`os.sendfile` if possible.
863 Return the total number of bytes sent.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200864
Yury Selivanov512d7102018-09-17 19:35:30 -0400865 Asynchronous version of :meth:`socket.sendfile() <socket.socket.sendfile>`.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200866
Yury Selivanov512d7102018-09-17 19:35:30 -0400867 *sock* must be a non-blocking :const:`socket.SOCK_STREAM`
868 :class:`~socket.socket`.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200869
Yury Selivanov512d7102018-09-17 19:35:30 -0400870 *file* must be a regular file object open in binary mode.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200871
872 *offset* tells from where to start reading the file. If specified,
873 *count* is the total number of bytes to transmit as opposed to
Yury Selivanov512d7102018-09-17 19:35:30 -0400874 sending the file until EOF is reached. File position is always updated,
875 even when this method raises an error, and
876 :meth:`file.tell() <io.IOBase.tell>` can be used to obtain the actual
877 number of bytes sent.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200878
Yury Selivanov512d7102018-09-17 19:35:30 -0400879 *fallback*, when set to ``True``, makes asyncio manually read and send
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200880 the file when the platform does not support the sendfile syscall
881 (e.g. Windows or SSL socket on Unix).
882
Andrew Svetlov7464e872018-01-19 20:04:29 +0200883 Raise :exc:`SendfileNotAvailableError` if the system does not support
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200884 *sendfile* syscall and *fallback* is ``False``.
885
Yury Selivanov512d7102018-09-17 19:35:30 -0400886 *sock* must be a non-blocking socket.
887
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200888 .. versionadded:: 3.7
889
Victor Stinnerc1567df2014-02-08 23:22:58 +0100890
Yury Selivanov512d7102018-09-17 19:35:30 -0400891DNS
892^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100893
Yury Selivanov512d7102018-09-17 19:35:30 -0400894.. coroutinemethod:: loop.getaddrinfo(host, port, \*, family=0, \
895 type=0, proto=0, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100896
Yury Selivanov512d7102018-09-17 19:35:30 -0400897 Asynchronous version of :meth:`socket.getaddrinfo`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100898
Yury Selivanov512d7102018-09-17 19:35:30 -0400899.. coroutinemethod:: loop.getnameinfo(sockaddr, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100900
Yury Selivanov512d7102018-09-17 19:35:30 -0400901 Asynchronous version of :meth:`socket.getnameinfo`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100902
Yury Selivanovbec23722018-01-28 14:09:40 -0500903.. versionchanged:: 3.7
904 Both *getaddrinfo* and *getnameinfo* methods were always documented
905 to return a coroutine, but prior to Python 3.7 they were, in fact,
906 returning :class:`asyncio.Future` objects. Starting with Python 3.7
907 both methods are coroutines.
908
Victor Stinnerea3183f2013-12-03 01:08:00 +0100909
Yury Selivanov512d7102018-09-17 19:35:30 -0400910Working with pipes
911^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100912
Yury Selivanov512d7102018-09-17 19:35:30 -0400913.. coroutinemethod:: loop.connect_read_pipe(protocol_factory, pipe)
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200914
Yury Selivanov512d7102018-09-17 19:35:30 -0400915 Register the read end of *pipe* in the event loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100916
Yury Selivanov512d7102018-09-17 19:35:30 -0400917 *protocol_factory* must be a callable returning an
918 :ref:`asyncio protocol <asyncio-protocol>` implementation.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100919
Yury Selivanov512d7102018-09-17 19:35:30 -0400920 *pipe* is a :term:`file-like object <file object>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100921
Victor Stinner2cef3002014-10-23 22:38:46 +0200922 Return pair ``(transport, protocol)``, where *transport* supports
Yury Selivanov512d7102018-09-17 19:35:30 -0400923 the :class:`ReadTransport` interface and *protocol* is an object
924 instantiated by the *protocol_factory*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100925
Victor Stinnerd84fd732014-08-26 01:01:59 +0200926 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
927 non-blocking mode.
928
Yury Selivanov512d7102018-09-17 19:35:30 -0400929.. coroutinemethod:: loop.connect_write_pipe(protocol_factory, pipe)
930
931 Register the write end of *pipe* in the event loop.
932
933 *protocol_factory* must be a callable returning an
934 :ref:`asyncio protocol <asyncio-protocol>` implementation.
935
936 *pipe* is :term:`file-like object <file object>`.
937
938 Return pair ``(transport, protocol)``, where *transport* supports
939 :class:`WriteTransport` interface and *protocol* is an object
940 instantiated by the *protocol_factory*.
941
942 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
943 non-blocking mode.
944
945.. note::
946
947 :class:`SelectorEventLoop` does not support the above methods on
948 Windows. Use :class:`ProactorEventLoop` instead for Windows.
949
Victor Stinner08444382014-02-02 22:43:39 +0100950.. seealso::
951
Yury Selivanov512d7102018-09-17 19:35:30 -0400952 The :meth:`loop.subprocess_exec` and
953 :meth:`loop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100954
Victor Stinnerea3183f2013-12-03 01:08:00 +0100955
Yury Selivanov512d7102018-09-17 19:35:30 -0400956Unix signals
957^^^^^^^^^^^^
Victor Stinner8b863482014-01-27 10:07:50 +0100958
Yury Selivanov512d7102018-09-17 19:35:30 -0400959.. method:: loop.add_signal_handler(signum, callback, \*args)
Victor Stinner8b863482014-01-27 10:07:50 +0100960
Yury Selivanov512d7102018-09-17 19:35:30 -0400961 Set *callback* as the handler for the *signum* signal.
Victor Stinner8b863482014-01-27 10:07:50 +0100962
Miss Islington (bot)12f39792018-12-18 13:52:37 -0800963 The callback will be invoked by *loop*, along with other queued callbacks
964 and runnable coroutines of that event loop. Unlike signal handlers
965 registered using :func:`signal.signal`, a callback registered with this
966 function is allowed to interact with the event loop.
967
Victor Stinner8b863482014-01-27 10:07:50 +0100968 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
969 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
970
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -0700971 Use :func:`functools.partial` :ref:`to pass keyword arguments
Miss Islington (bot)6627d3a2018-12-03 23:36:31 -0800972 <asyncio-pass-keywords>` to *callback*.
Victor Stinner8464c242014-11-28 13:15:41 +0100973
Miss Islington (bot)12f39792018-12-18 13:52:37 -0800974 Like :func:`signal.signal`, this function must be invoked in the main
975 thread.
976
Yury Selivanov512d7102018-09-17 19:35:30 -0400977.. method:: loop.remove_signal_handler(sig)
Victor Stinner8b863482014-01-27 10:07:50 +0100978
Yury Selivanov512d7102018-09-17 19:35:30 -0400979 Remove the handler for the *sig* signal.
Victor Stinner8b863482014-01-27 10:07:50 +0100980
Yury Selivanov512d7102018-09-17 19:35:30 -0400981 Return ``True`` if the signal handler was removed, or ``False`` if
982 no handler was set for the given signal.
983
Cheryl Sabellab248a8c2018-10-15 16:52:26 -0400984 .. availability:: Unix.
Victor Stinner8b863482014-01-27 10:07:50 +0100985
986.. seealso::
987
988 The :mod:`signal` module.
989
990
Yury Selivanov512d7102018-09-17 19:35:30 -0400991Executing code in thread or process pools
992^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100993
Miss Islington (bot)73c00062018-09-18 15:09:51 -0700994.. awaitablemethod:: loop.run_in_executor(executor, func, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100995
Yury Selivanov512d7102018-09-17 19:35:30 -0400996 Arrange for *func* to be called in the specified executor.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100997
Yury Selivanov512d7102018-09-17 19:35:30 -0400998 The *executor* argument should be an :class:`concurrent.futures.Executor`
Larry Hastings3732ed22014-03-15 21:13:56 -0700999 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +01001000
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -07001001 Example::
1002
1003 import asyncio
1004 import concurrent.futures
1005
1006 def blocking_io():
1007 # File operations (such as logging) can block the
1008 # event loop: run them in a thread pool.
1009 with open('/dev/urandom', 'rb') as f:
1010 return f.read(100)
1011
1012 def cpu_bound():
1013 # CPU-bound operations will block the event loop:
1014 # in general it is preferable to run them in a
1015 # process pool.
1016 return sum(i * i for i in range(10 ** 7))
1017
1018 async def main():
1019 loop = asyncio.get_running_loop()
1020
1021 ## Options:
1022
1023 # 1. Run in the default loop's executor:
1024 result = await loop.run_in_executor(
1025 None, blocking_io)
1026 print('default thread pool', result)
1027
1028 # 2. Run in a custom thread pool:
1029 with concurrent.futures.ThreadPoolExecutor() as pool:
1030 result = await loop.run_in_executor(
1031 pool, blocking_io)
1032 print('custom thread pool', result)
1033
1034 # 3. Run in a custom process pool:
1035 with concurrent.futures.ProcessPoolExecutor() as pool:
1036 result = await loop.run_in_executor(
1037 pool, cpu_bound)
1038 print('custom process pool', result)
1039
1040 asyncio.run(main())
Victor Stinner8464c242014-11-28 13:15:41 +01001041
Yury Selivanovbec23722018-01-28 14:09:40 -05001042 This method returns a :class:`asyncio.Future` object.
1043
Miss Islington (bot)8e5ef582018-09-20 09:57:19 -07001044 Use :func:`functools.partial` :ref:`to pass keyword arguments
1045 <asyncio-pass-keywords>` to *func*.
1046
Yury Selivanove8a60452016-10-21 17:40:42 -04001047 .. versionchanged:: 3.5.3
Yury Selivanov512d7102018-09-17 19:35:30 -04001048 :meth:`loop.run_in_executor` no longer configures the
Yury Selivanove8a60452016-10-21 17:40:42 -04001049 ``max_workers`` of the thread pool executor it creates, instead
1050 leaving it up to the thread pool executor
1051 (:class:`~concurrent.futures.ThreadPoolExecutor`) to set the
1052 default.
1053
Yury Selivanov512d7102018-09-17 19:35:30 -04001054.. method:: loop.set_default_executor(executor)
Victor Stinnerea3183f2013-12-03 01:08:00 +01001055
Yury Selivanov512d7102018-09-17 19:35:30 -04001056 Set *executor* as the default executor used by :meth:`run_in_executor`.
1057 *executor* should be an instance of
1058 :class:`~concurrent.futures.ThreadPoolExecutor`.
1059
1060 .. deprecated:: 3.7
1061 Using an executor that is not an instance of
1062 :class:`~concurrent.futures.ThreadPoolExecutor` is deprecated and
1063 will trigger an error in Python 3.9.
1064
1065 *executor* must be an instance of
1066 :class:`concurrent.futures.ThreadPoolExecutor`.
Victor Stinnerea3183f2013-12-03 01:08:00 +01001067
1068
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001069Error Handling API
Yury Selivanov512d7102018-09-17 19:35:30 -04001070^^^^^^^^^^^^^^^^^^
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001071
Martin Panterc04fb562016-02-10 05:44:01 +00001072Allows customizing how exceptions are handled in the event loop.
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001073
Yury Selivanov512d7102018-09-17 19:35:30 -04001074.. method:: loop.set_exception_handler(handler)
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001075
1076 Set *handler* as the new event loop exception handler.
1077
1078 If *handler* is ``None``, the default exception handler will
Yury Selivanov512d7102018-09-17 19:35:30 -04001079 be set. Otherwise, *handler* must be a callable with the signature
1080 matching ``(loop, context)``, where ``loop``
1081 is a reference to the active event loop, and ``context``
1082 is a ``dict`` object containing the details of the exception
1083 (see :meth:`call_exception_handler` documentation for details
1084 about context).
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001085
Yury Selivanov512d7102018-09-17 19:35:30 -04001086.. method:: loop.get_exception_handler()
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001087
Yury Selivanov512d7102018-09-17 19:35:30 -04001088 Return the current exception handler, or ``None`` if no custom
1089 exception handler was set.
Yury Selivanov950204d2016-05-16 16:23:00 -04001090
1091 .. versionadded:: 3.5.2
1092
Yury Selivanov512d7102018-09-17 19:35:30 -04001093.. method:: loop.default_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001094
1095 Default exception handler.
1096
1097 This is called when an exception occurs and no exception
Yury Selivanov512d7102018-09-17 19:35:30 -04001098 handler is set. This can be called by a custom exception
1099 handler that wants to defer to the default handler behavior.
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001100
1101 *context* parameter has the same meaning as in
1102 :meth:`call_exception_handler`.
1103
Yury Selivanov512d7102018-09-17 19:35:30 -04001104.. method:: loop.call_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001105
1106 Call the current event loop exception handler.
1107
1108 *context* is a ``dict`` object containing the following keys
Yury Selivanov512d7102018-09-17 19:35:30 -04001109 (new keys may be introduced in future Python versions):
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001110
1111 * 'message': Error message;
1112 * 'exception' (optional): Exception object;
1113 * 'future' (optional): :class:`asyncio.Future` instance;
1114 * 'handle' (optional): :class:`asyncio.Handle` instance;
1115 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
1116 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
1117 * 'socket' (optional): :class:`socket.socket` instance.
1118
1119 .. note::
1120
Yury Selivanov512d7102018-09-17 19:35:30 -04001121 This method should not be overloaded in subclassed
1122 event loops. For custom exception handling, use
1123 the :meth:`set_exception_handler()` method.
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001124
Yury Selivanov512d7102018-09-17 19:35:30 -04001125Enabling debug mode
1126^^^^^^^^^^^^^^^^^^^
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001127
Yury Selivanov512d7102018-09-17 19:35:30 -04001128.. method:: loop.get_debug()
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001129
Victor Stinner7b7120e2014-06-23 00:12:14 +02001130 Get the debug mode (:class:`bool`) of the event loop.
1131
1132 The default value is ``True`` if the environment variable
1133 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
1134 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001135
Yury Selivanov512d7102018-09-17 19:35:30 -04001136.. method:: loop.set_debug(enabled: bool)
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001137
1138 Set the debug mode of the event loop.
1139
Yury Selivanov512d7102018-09-17 19:35:30 -04001140 .. versionchanged:: 3.7
1141
1142 The new ``-X dev`` command line option can now also be used
1143 to enable the debug mode.
Victor Stinner64d750b2014-06-18 03:25:23 +02001144
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001145.. seealso::
1146
Victor Stinner62511fd2014-06-23 00:36:11 +02001147 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001148
Yury Selivanov512d7102018-09-17 19:35:30 -04001149
1150Running Subprocesses
1151^^^^^^^^^^^^^^^^^^^^
1152
1153Methods described in this subsections are low-level. In regular
1154async/await code consider using the high-level
1155:func:`asyncio.create_subprocess_shell` and
1156:func:`asyncio.create_subprocess_exec` convenience functions instead.
1157
1158.. note::
1159
1160 The default asyncio event loop on **Windows** does not support
1161 subprocesses. See :ref:`Subprocess Support on Windows
1162 <asyncio-windows-subprocess>` for details.
1163
1164.. coroutinemethod:: loop.subprocess_exec(protocol_factory, \*args, \
1165 stdin=subprocess.PIPE, stdout=subprocess.PIPE, \
1166 stderr=subprocess.PIPE, \*\*kwargs)
1167
1168 Create a subprocess from one or more string arguments specified by
1169 *args*.
1170
1171 *args* must be a list of strings represented by:
1172
1173 * :class:`str`;
1174 * or :class:`bytes`, encoded to the
1175 :ref:`filesystem encoding <filesystem-encoding>`.
1176
1177 The first string specifies the program executable,
1178 and the remaining strings specify the arguments. Together, string
1179 arguments form the ``argv`` of the program.
1180
1181 This is similar to the standard library :class:`subprocess.Popen`
1182 class called with ``shell=False`` and the list of strings passed as
1183 the first argument; however, where :class:`~subprocess.Popen` takes
1184 a single argument which is list of strings, *subprocess_exec*
1185 takes multiple string arguments.
1186
1187 The *protocol_factory* must be a callable returning a subclass of the
1188 :class:`asyncio.SubprocessProtocol` class.
1189
1190 Other parameters:
1191
1192 * *stdin*: either a file-like object representing a pipe to be
1193 connected to the subprocess's standard input stream using
1194 :meth:`~loop.connect_write_pipe`, or the
1195 :const:`subprocess.PIPE` constant (default). By default a new
1196 pipe will be created and connected.
1197
1198 * *stdout*: either a file-like object representing the pipe to be
1199 connected to the subprocess's standard output stream using
1200 :meth:`~loop.connect_read_pipe`, or the
1201 :const:`subprocess.PIPE` constant (default). By default a new pipe
1202 will be created and connected.
1203
1204 * *stderr*: either a file-like object representing the pipe to be
1205 connected to the subprocess's standard error stream using
1206 :meth:`~loop.connect_read_pipe`, or one of
1207 :const:`subprocess.PIPE` (default) or :const:`subprocess.STDOUT`
1208 constants.
1209
1210 By default a new pipe will be created and connected. When
1211 :const:`subprocess.STDOUT` is specified, the subprocess' standard
1212 error stream will be connected to the same pipe as the standard
1213 output stream.
1214
1215 * All other keyword arguments are passed to :class:`subprocess.Popen`
1216 without interpretation, except for *bufsize*, *universal_newlines*
1217 and *shell*, which should not be specified at all.
1218
1219 See the constructor of the :class:`subprocess.Popen` class
1220 for documentation on other arguments.
1221
1222 Returns a pair of ``(transport, protocol)``, where *transport*
1223 conforms to the :class:`asyncio.SubprocessTransport` base class and
1224 *protocol* is an object instantiated by the *protocol_factory*.
1225
1226.. coroutinemethod:: loop.subprocess_shell(protocol_factory, cmd, \*, \
1227 stdin=subprocess.PIPE, stdout=subprocess.PIPE, \
1228 stderr=subprocess.PIPE, \*\*kwargs)
1229
1230 Create a subprocess from *cmd*, which can be a :class:`str` or a
1231 :class:`bytes` string encoded to the
1232 :ref:`filesystem encoding <filesystem-encoding>`,
1233 using the platform's "shell" syntax.
1234
1235 This is similar to the standard library :class:`subprocess.Popen`
1236 class called with ``shell=True``.
1237
1238 The *protocol_factory* must be a callable returning a subclass of the
1239 :class:`SubprocessProtocol` class.
1240
1241 See :meth:`~loop.subprocess_exec` for more details about
1242 the remaining arguments.
1243
1244 Returns a pair of ``(transport, protocol)``, where *transport*
1245 conforms to the :class:`SubprocessTransport` base class and
1246 *protocol* is an object instantiated by the *protocol_factory*.
1247
1248.. note::
1249 It is the application's responsibility to ensure that all whitespace
1250 and special characters are quoted appropriately to avoid `shell injection
1251 <https://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_
1252 vulnerabilities. The :func:`shlex.quote` function can be used to
1253 properly escape whitespace and special characters in strings that
1254 are going to be used to construct shell commands.
1255
1256
1257Callback Handles
1258================
1259
1260.. class:: Handle
1261
1262 A callback wrapper object returned by :meth:`loop.call_soon`,
1263 :meth:`loop.call_soon_threadsafe`.
1264
1265 .. method:: cancel()
1266
1267 Cancel the callback. If the callback has already been canceled
1268 or executed, this method has no effect.
1269
1270 .. method:: cancelled()
1271
1272 Return ``True`` if the callback was cancelled.
1273
1274 .. versionadded:: 3.7
1275
1276.. class:: TimerHandle
1277
1278 A callback wrapper object returned by :meth:`loop.call_later`,
1279 and :meth:`loop.call_at`.
1280
1281 This class is a subclass of :class:`Handle`.
1282
1283 .. method:: when()
1284
1285 Return a scheduled callback time as :class:`float` seconds.
1286
1287 The time is an absolute timestamp, using the same time
1288 reference as :meth:`loop.time`.
1289
1290 .. versionadded:: 3.7
1291
1292
1293Server Objects
1294==============
1295
1296Server objects are created by :meth:`loop.create_server`,
1297:meth:`loop.create_unix_server`, :func:`start_server`,
1298and :func:`start_unix_server` functions.
1299
1300Do not instantiate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +01001301
Victor Stinner8ebeb032014-07-11 23:47:40 +02001302.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +01001303
Yury Selivanovc9070d02018-01-25 18:08:09 -05001304 *Server* objects are asynchronous context managers. When used in an
1305 ``async with`` statement, it's guaranteed that the Server object is
1306 closed and not accepting new connections when the ``async with``
1307 statement is completed::
1308
1309 srv = await loop.create_server(...)
1310
1311 async with srv:
1312 # some code
1313
1314 # At this point, srv is closed and no longer accepts new connections.
1315
1316
1317 .. versionchanged:: 3.7
1318 Server object is an asynchronous context manager since Python 3.7.
Victor Stinner8c462c52014-01-24 18:11:43 +01001319
1320 .. method:: close()
1321
Victor Stinner4bfb14a2014-07-12 03:20:24 +02001322 Stop serving: close listening sockets and set the :attr:`sockets`
1323 attribute to ``None``.
1324
Yury Selivanov512d7102018-09-17 19:35:30 -04001325 The sockets that represent existing incoming client connections
1326 are left open.
Victor Stinner8ebeb032014-07-11 23:47:40 +02001327
Berker Peksag49c9edf2016-01-20 07:14:22 +02001328 The server is closed asynchronously, use the :meth:`wait_closed`
1329 coroutine to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +01001330
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +05301331 .. method:: get_loop()
1332
Yury Selivanov512d7102018-09-17 19:35:30 -04001333 Return the event loop associated with the server object.
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +05301334
1335 .. versionadded:: 3.7
1336
Yury Selivanovc9070d02018-01-25 18:08:09 -05001337 .. coroutinemethod:: start_serving()
1338
1339 Start accepting connections.
1340
1341 This method is idempotent, so it can be called when
1342 the server is already being serving.
1343
Yury Selivanov512d7102018-09-17 19:35:30 -04001344 The *start_serving* keyword-only parameter to
1345 :meth:`loop.create_server` and
1346 :meth:`asyncio.start_server` allows creating a Server object
1347 that is not accepting connections initially. In this case
1348 ``Server.start_serving()``, or :meth:`Server.serve_forever` can be used
1349 to make the Server start accepting connections.
Yury Selivanovc9070d02018-01-25 18:08:09 -05001350
1351 .. versionadded:: 3.7
1352
1353 .. coroutinemethod:: serve_forever()
1354
1355 Start accepting connections until the coroutine is cancelled.
1356 Cancellation of ``serve_forever`` task causes the server
1357 to be closed.
1358
1359 This method can be called if the server is already accepting
1360 connections. Only one ``serve_forever`` task can exist per
1361 one *Server* object.
1362
1363 Example::
1364
1365 async def client_connected(reader, writer):
1366 # Communicate with the client with
1367 # reader/writer streams. For example:
1368 await reader.readline()
1369
1370 async def main(host, port):
1371 srv = await asyncio.start_server(
1372 client_connected, host, port)
Miss Islington (bot)aeb5d732018-02-17 10:02:46 -08001373 await srv.serve_forever()
Yury Selivanovc9070d02018-01-25 18:08:09 -05001374
1375 asyncio.run(main('127.0.0.1', 0))
1376
1377 .. versionadded:: 3.7
1378
1379 .. method:: is_serving()
1380
1381 Return ``True`` if the server is accepting new connections.
1382
1383 .. versionadded:: 3.7
1384
Victor Stinnerbdd574d2015-02-12 22:49:18 +01001385 .. coroutinemethod:: wait_closed()
Victor Stinner8c462c52014-01-24 18:11:43 +01001386
Victor Stinner8ebeb032014-07-11 23:47:40 +02001387 Wait until the :meth:`close` method completes.
1388
Victor Stinner8ebeb032014-07-11 23:47:40 +02001389 .. attribute:: sockets
1390
Yury Selivanov512d7102018-09-17 19:35:30 -04001391 List of :class:`socket.socket` objects the server is listening on,
1392 or ``None`` if the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +01001393
Yury Selivanovc9070d02018-01-25 18:08:09 -05001394 .. versionchanged:: 3.7
Yury Selivanov512d7102018-09-17 19:35:30 -04001395 Prior to Python 3.7 ``Server.sockets`` used to return an
1396 internal list of server sockets directly. In 3.7 a copy
Yury Selivanovc9070d02018-01-25 18:08:09 -05001397 of that list is returned.
1398
Victor Stinner8c462c52014-01-24 18:11:43 +01001399
Yury Selivanov512d7102018-09-17 19:35:30 -04001400.. _asyncio-event-loops:
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001401
Yury Selivanov512d7102018-09-17 19:35:30 -04001402Event Loop Implementations
1403==========================
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001404
Yury Selivanov512d7102018-09-17 19:35:30 -04001405asyncio ships with two different event loop implementations:
1406:class:`SelectorEventLoop` and :class:`ProactorEventLoop`.
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001407
Yury Selivanov512d7102018-09-17 19:35:30 -04001408By default asyncio is configured to use :class:`SelectorEventLoop`
1409on all platforms.
Miss Islington (bot)71a0b0e2018-02-01 11:56:03 -08001410
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001411
Yury Selivanov512d7102018-09-17 19:35:30 -04001412.. class:: SelectorEventLoop
1413
1414 An event loop based on the :mod:`selectors` module.
1415
1416 Uses the most efficient *selector* available for the given
1417 platform. It is also possible to manually configure the
1418 exact selector implementation to be used::
1419
1420 import asyncio
1421 import selectors
1422
1423 selector = selectors.SelectSelector()
1424 loop = asyncio.SelectorEventLoop(selector)
1425 asyncio.set_event_loop(loop)
Andrew Svetlov7464e872018-01-19 20:04:29 +02001426
1427
Cheryl Sabellab248a8c2018-10-15 16:52:26 -04001428 .. availability:: Unix, Windows.
Andrew Svetlov7464e872018-01-19 20:04:29 +02001429
1430
Yury Selivanov512d7102018-09-17 19:35:30 -04001431.. class:: ProactorEventLoop
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001432
Yury Selivanov512d7102018-09-17 19:35:30 -04001433 An event loop for Windows that uses "I/O Completion Ports" (IOCP).
1434
Cheryl Sabellab248a8c2018-10-15 16:52:26 -04001435 .. availability:: Windows.
Yury Selivanov512d7102018-09-17 19:35:30 -04001436
1437 An example how to use :class:`ProactorEventLoop` on Windows::
1438
1439 import asyncio
1440 import sys
1441
1442 if sys.platform == 'win32':
1443 loop = asyncio.ProactorEventLoop()
1444 asyncio.set_event_loop(loop)
1445
1446 .. seealso::
1447
1448 `MSDN documentation on I/O Completion Ports
1449 <https://docs.microsoft.com/en-ca/windows/desktop/FileIO/i-o-completion-ports>`_.
1450
1451
1452.. class:: AbstractEventLoop
1453
1454 Abstract base class for asyncio-compliant event loops.
1455
1456 The :ref:`Event Loop Methods <asyncio-event-loop>` section lists all
1457 methods that an alternative implementation of ``AbstractEventLoop``
1458 should have defined.
1459
1460
1461Examples
1462========
1463
1464Note that all examples in this section **purposefully** show how
1465to use the low-level event loop APIs, such as :meth:`loop.run_forever`
1466and :meth:`loop.call_soon`. Modern asyncio applications rarely
1467need to be written this way; consider using the high-level functions
1468like :func:`asyncio.run`.
1469
1470
1471.. _asyncio_example_lowlevel_helloworld:
Victor Stinnerea3183f2013-12-03 01:08:00 +01001472
Victor Stinner7f314ed2014-10-15 18:49:16 +02001473Hello World with call_soon()
Victor Stinnera092a612015-01-09 15:58:41 +01001474^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +01001475
Yury Selivanov512d7102018-09-17 19:35:30 -04001476An example using the :meth:`loop.call_soon` method to schedule a
1477callback. The callback displays ``"Hello World"`` and then stops the
1478event loop::
Victor Stinnerea3183f2013-12-03 01:08:00 +01001479
1480 import asyncio
1481
Victor Stinner7f314ed2014-10-15 18:49:16 +02001482 def hello_world(loop):
Yury Selivanov512d7102018-09-17 19:35:30 -04001483 """A callback to print 'Hello World' and stop the event loop"""
Victor Stinnerea3183f2013-12-03 01:08:00 +01001484 print('Hello World')
Victor Stinner7f314ed2014-10-15 18:49:16 +02001485 loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +01001486
1487 loop = asyncio.get_event_loop()
Victor Stinner7f314ed2014-10-15 18:49:16 +02001488
1489 # Schedule a call to hello_world()
1490 loop.call_soon(hello_world, loop)
1491
1492 # Blocking call interrupted by loop.stop()
Yury Selivanov512d7102018-09-17 19:35:30 -04001493 try:
1494 loop.run_forever()
1495 finally:
1496 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +01001497
Victor Stinner3e09e322013-12-03 01:22:06 +01001498.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +01001499
Yury Selivanov512d7102018-09-17 19:35:30 -04001500 A similar :ref:`Hello World <coroutine>`
1501 example created with a coroutine and the :func:`run` function.
Victor Stinnerea3183f2013-12-03 01:08:00 +01001502
Victor Stinner8b863482014-01-27 10:07:50 +01001503
Yury Selivanov512d7102018-09-17 19:35:30 -04001504.. _asyncio_example_call_later:
Victor Stinner7f314ed2014-10-15 18:49:16 +02001505
1506Display the current date with call_later()
Victor Stinnera092a612015-01-09 15:58:41 +01001507^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner7f314ed2014-10-15 18:49:16 +02001508
Yury Selivanov512d7102018-09-17 19:35:30 -04001509An example of a callback displaying the current date every second. The
1510callback uses the :meth:`loop.call_later` method to reschedule itself
1511after 5 seconds, and then stops the event loop::
Victor Stinner7f314ed2014-10-15 18:49:16 +02001512
1513 import asyncio
1514 import datetime
1515
1516 def display_date(end_time, loop):
1517 print(datetime.datetime.now())
1518 if (loop.time() + 1.0) < end_time:
1519 loop.call_later(1, display_date, end_time, loop)
1520 else:
1521 loop.stop()
1522
1523 loop = asyncio.get_event_loop()
1524
1525 # Schedule the first call to display_date()
1526 end_time = loop.time() + 5.0
1527 loop.call_soon(display_date, end_time, loop)
1528
1529 # Blocking call interrupted by loop.stop()
Yury Selivanov512d7102018-09-17 19:35:30 -04001530 try:
1531 loop.run_forever()
1532 finally:
1533 loop.close()
Victor Stinner7f314ed2014-10-15 18:49:16 +02001534
1535.. seealso::
1536
Yury Selivanov512d7102018-09-17 19:35:30 -04001537 A similar :ref:`current date <asyncio_example_sleep>` example
1538 created with a coroutine and the :func:`run` function.
Victor Stinner7f314ed2014-10-15 18:49:16 +02001539
1540
Yury Selivanov512d7102018-09-17 19:35:30 -04001541.. _asyncio_example_watch_fd:
Victor Stinner8b863482014-01-27 10:07:50 +01001542
Victor Stinner04e6df32014-10-11 16:16:27 +02001543Watch a file descriptor for read events
Victor Stinnera092a612015-01-09 15:58:41 +01001544^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +02001545
1546Wait until a file descriptor received some data using the
Yury Selivanov512d7102018-09-17 19:35:30 -04001547:meth:`loop.add_reader` method and then close the event loop::
Victor Stinner04e6df32014-10-11 16:16:27 +02001548
1549 import asyncio
Victor Stinnerac577d72017-11-28 21:33:20 +01001550 from socket import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +02001551
1552 # Create a pair of connected file descriptors
Victor Stinnerccd8e342014-10-11 16:30:02 +02001553 rsock, wsock = socketpair()
Yury Selivanov512d7102018-09-17 19:35:30 -04001554
Victor Stinner04e6df32014-10-11 16:16:27 +02001555 loop = asyncio.get_event_loop()
1556
1557 def reader():
1558 data = rsock.recv(100)
1559 print("Received:", data.decode())
Yury Selivanov512d7102018-09-17 19:35:30 -04001560
Victor Stinner2cef3002014-10-23 22:38:46 +02001561 # We are done: unregister the file descriptor
Victor Stinner04e6df32014-10-11 16:16:27 +02001562 loop.remove_reader(rsock)
Yury Selivanov512d7102018-09-17 19:35:30 -04001563
Victor Stinner04e6df32014-10-11 16:16:27 +02001564 # Stop the event loop
1565 loop.stop()
1566
Victor Stinner2cef3002014-10-23 22:38:46 +02001567 # Register the file descriptor for read event
Victor Stinner04e6df32014-10-11 16:16:27 +02001568 loop.add_reader(rsock, reader)
1569
1570 # Simulate the reception of data from the network
1571 loop.call_soon(wsock.send, 'abc'.encode())
1572
Yury Selivanov512d7102018-09-17 19:35:30 -04001573 try:
1574 # Run the event loop
1575 loop.run_forever()
1576 finally:
1577 # We are done. Close sockets and the event loop.
1578 rsock.close()
1579 wsock.close()
1580 loop.close()
Victor Stinner04e6df32014-10-11 16:16:27 +02001581
1582.. seealso::
1583
Yury Selivanov512d7102018-09-17 19:35:30 -04001584 * A similar :ref:`example <asyncio_example_create_connection>`
1585 using transports, protocols, and the
1586 :meth:`loop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +02001587
Yury Selivanov512d7102018-09-17 19:35:30 -04001588 * Another similar :ref:`example <asyncio_example_create_connection-streams>`
1589 using the high-level :func:`asyncio.open_connection` function
1590 and streams.
Victor Stinner04e6df32014-10-11 16:16:27 +02001591
1592
Yury Selivanov512d7102018-09-17 19:35:30 -04001593.. _asyncio_example_unix_signals:
1594
Victor Stinner04e6df32014-10-11 16:16:27 +02001595Set signal handlers for SIGINT and SIGTERM
Victor Stinnera092a612015-01-09 15:58:41 +01001596^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +02001597
Yury Selivanov512d7102018-09-17 19:35:30 -04001598(This ``signals`` example only works on Unix.)
1599
1600Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`
1601using the :meth:`loop.add_signal_handler` method::
Victor Stinner8b863482014-01-27 10:07:50 +01001602
1603 import asyncio
1604 import functools
1605 import os
1606 import signal
1607
1608 def ask_exit(signame):
1609 print("got signal %s: exit" % signame)
1610 loop.stop()
1611
Yury Selivanov512d7102018-09-17 19:35:30 -04001612 async def main():
1613 loop = asyncio.get_running_loop()
Victor Stinner8b863482014-01-27 10:07:50 +01001614
Yury Selivanov512d7102018-09-17 19:35:30 -04001615 for signame in {'SIGINT', 'SIGTERM'}:
1616 loop.add_signal_handler(
1617 getattr(signal, signame),
1618 functools.partial(ask_exit, signame))
Victor Stinner2cef3002014-10-23 22:38:46 +02001619
Yury Selivanov512d7102018-09-17 19:35:30 -04001620 await asyncio.sleep(3600)
1621
1622 print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
1623 print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")
1624
1625 asyncio.run(main())