blob: 718c32277c2752def6a4d666afbaa176cfe2c6ea [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
8
9.. rubric:: Preface
10
Carol Willing5b7cbd62018-09-12 17:05:17 -070011The event loop is a central component of every asyncio application.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070012Event loops run asynchronous tasks and callbacks, perform network
Carol Willing5b7cbd62018-09-12 17:05:17 -070013IO operations, and run subprocesses.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070014
Carol Willing5b7cbd62018-09-12 17:05:17 -070015Application developers will typically use high-level asyncio functions
16to interact with the event loop. In general, high-level asyncio applications
17should not need to work directly with event loops and, instead, should use
18the :func:`asyncio.run` function to initialize, manage the event loop, and
19run asynchronous code.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070020
Carol Willing5b7cbd62018-09-12 17:05:17 -070021Alternatively, developers of low-level code, such as libraries and
22framework, may need access to the event loop.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070023
24.. rubric:: Accessing Event Loop
25
26The following low-level functions can be used to get, set, or create
27an event loop:
28
29.. function:: get_running_loop()
30
31 Return the running event loop in the current OS thread.
32
33 If there is no running event loop a :exc:`RuntimeError` is raised.
34 This function can only be called from a coroutine or a callback.
35
36 .. versionadded:: 3.7
37
38.. function:: get_event_loop()
39
40 Get the current event loop. If there is no current event loop set
41 in the current OS thread and :func:`set_event_loop` has not yet
42 been called, asyncio will create a new event loop and set it as the
43 current one.
44
Carol Willing5b7cbd62018-09-12 17:05:17 -070045 Because this function has rather complex behavior (especially
46 when custom event loop policies are in use), using the
47 :func:`get_running_loop` function is preferred to :func:`get_event_loop`
48 in coroutines and callbacks.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070049
Carol Willing5b7cbd62018-09-12 17:05:17 -070050 Consider also using the :func:`asyncio.run` function instead of using
51 lower level functions to manually create and close an event loop.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070052
53.. function:: set_event_loop(loop)
54
55 Set *loop* as a current event loop for the current OS thread.
56
57.. function:: new_event_loop()
58
59 Create a new event loop object.
60
61Note that the behaviour of :func:`get_event_loop`, :func:`set_event_loop`,
62and :func:`new_event_loop` functions can be altered by
63:ref:`setting a custom event loop policy <asyncio-policies>`.
64
65
66.. rubric:: Contents
67
68This documentation page contains the following sections:
69
Carol Willing5b7cbd62018-09-12 17:05:17 -070070* The `Event Loop Methods`_ section is the reference documentation of
Yury Selivanov7c7605f2018-09-11 09:54:40 -070071 event loop APIs;
72
73* The `Callback Handles`_ section documents the :class:`Handle` and
Carol Willing5b7cbd62018-09-12 17:05:17 -070074 :class:`TimerHandle`, instances which are returned from functions, such
75 as :meth:`loop.call_soon` and :meth:`loop.call_later`;
Yury Selivanov7c7605f2018-09-11 09:54:40 -070076
Carol Willing5b7cbd62018-09-12 17:05:17 -070077* The `Server Objects`_ sections document types returned from
Yury Selivanov7c7605f2018-09-11 09:54:40 -070078 event loop methods like :meth:`loop.create_server`;
79
80* The `Event Loops Implementations`_ section documents the
81 :class:`SelectorEventLoop` and :class:`ProactorEventLoop` classes;
82
83* The `Examples`_ section showcases how to work with some event
84 loop APIs.
85
86
Victor Stinner9592edb2014-02-02 15:03:02 +010087.. _asyncio-event-loop:
Victor Stinnerea3183f2013-12-03 01:08:00 +010088
Yury Selivanov7c7605f2018-09-11 09:54:40 -070089Event Loop Methods
90==================
Victor Stinnerea3183f2013-12-03 01:08:00 +010091
Carol Willing5b7cbd62018-09-12 17:05:17 -070092Event loops have **low-level** APIs for the following:
lf627d2c82017-07-25 17:03:51 -060093
Yury Selivanov7c7605f2018-09-11 09:54:40 -070094.. contents::
95 :depth: 1
96 :local:
Victor Stinnerea3183f2013-12-03 01:08:00 +010097
Victor Stinnerea3183f2013-12-03 01:08:00 +010098
Yury Selivanov7c7605f2018-09-11 09:54:40 -070099Running and stopping the loop
100^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100101
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700102.. method:: loop.run_until_complete(future)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100103
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700104 Run until the *future* (an instance of :class:`Future`) is
105 completed.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100106
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700107 If the argument is a :ref:`coroutine object <coroutine>` it
108 is implicitly wrapped into an :class:`asyncio.Task`.
Eli Bendersky136fea22014-02-09 06:55:58 -0800109
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700110 Return the Future's result or raise its exception.
Guido van Rossumf68afd82016-08-08 09:41:21 -0700111
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700112.. method:: loop.run_forever()
Guido van Rossumf68afd82016-08-08 09:41:21 -0700113
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700114 Run the event loop until :meth:`stop` is called.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100115
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700116 If :meth:`stop` is called before :meth:`run_forever()` is called,
117 the loop will poll the I/O selector once with a timeout of zero,
118 run all callbacks scheduled in response to I/O events (and
119 those that were already scheduled), and then exit.
Victor Stinner83704962015-02-25 14:24:15 +0100120
Guido van Rossum41f69f42015-11-19 13:28:47 -0800121 If :meth:`stop` is called while :meth:`run_forever` is running,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700122 the loop will run the current batch of callbacks and then exit.
Carol Willing5b7cbd62018-09-12 17:05:17 -0700123 Note that callbacks scheduled by callbacks will not run in this
124 case; instead, they will run the next time :meth:`run_forever` or
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700125 :meth:`run_until_complete` is called.
Guido van Rossum41f69f42015-11-19 13:28:47 -0800126
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700127.. method:: loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100128
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700129 Stop the event loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100130
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700131.. method:: loop.is_running()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100132
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700133 Return ``True`` if the event loop is currently running.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100134
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700135.. method:: loop.is_closed()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100136
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700137 Return ``True`` if the event loop was closed.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100138
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700139.. method:: loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100140
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700141 Close the event loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100142
Carol Willing5b7cbd62018-09-12 17:05:17 -0700143 The loop must be running when this function is called.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700144 Any pending callbacks will be discarded.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100145
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700146 This method clears all queues and shuts down the executor, but does
147 not wait for the executor to finish.
Guido van Rossum41f69f42015-11-19 13:28:47 -0800148
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700149 This method is idempotent and irreversible. No other methods
150 should be called after the event loop is closed.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100151
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700152.. coroutinemethod:: loop.shutdown_asyncgens()
Yury Selivanov03660042016-12-15 17:36:05 -0500153
154 Schedule all currently open :term:`asynchronous generator` objects to
155 close with an :meth:`~agen.aclose()` call. After calling this method,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700156 the event loop will issue a warning if a new asynchronous generator
Carol Willing5b7cbd62018-09-12 17:05:17 -0700157 is iterated. This should be used to reliably finalize all scheduled
158 asynchronous generators, e.g.::
159
Yury Selivanov03660042016-12-15 17:36:05 -0500160
161 try:
162 loop.run_forever()
163 finally:
164 loop.run_until_complete(loop.shutdown_asyncgens())
165 loop.close()
166
167 .. versionadded:: 3.6
168
169
Victor Stinner8464c242014-11-28 13:15:41 +0100170.. _asyncio-pass-keywords:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100171
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700172Scheduling callbacks
173^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100174
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700175.. method:: loop.call_soon(callback, *args, context=None)
Victor Stinner8464c242014-11-28 13:15:41 +0100176
Carol Willing5b7cbd62018-09-12 17:05:17 -0700177 Schedule a *callback* to be called with *args* arguments at
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700178 the next iteration of the event loop.
Victor Stinner8464c242014-11-28 13:15:41 +0100179
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700180 Callbacks are called in the order in which they are registered.
181 Each callback will be called exactly once.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100182
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700183 An optional keyword-only *context* argument allows specifying a
184 custom :class:`contextvars.Context` for the *callback* to run in.
185 The current context is used when no *context* is provided.
Yury Selivanov28b91782018-05-23 13:35:04 -0400186
Yury Selivanov1096f762015-06-25 13:49:52 -0400187 An instance of :class:`asyncio.Handle` is returned, which can be
Carol Willing5b7cbd62018-09-12 17:05:17 -0700188 used later to cancel the callback.
189
190 This method is not thread-safe.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500191
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700192.. method:: loop.call_soon_threadsafe(callback, *args, context=None)
Victor Stinner8464c242014-11-28 13:15:41 +0100193
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700194 A thread-safe variant of :meth:`call_soon`. Must be used to
195 schedule callbacks *from another thread*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100196
Victor Stinner83704962015-02-25 14:24:15 +0100197 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
198 section of the documentation.
199
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700200.. versionchanged:: 3.7
201 The *context* keyword-only parameter was added. See :pep:`567`
202 for more details.
203
204.. note::
205
Carol Willing5b7cbd62018-09-12 17:05:17 -0700206 Most :mod:`asyncio` scheduling functions don't allow passing
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700207 keyword arguments. To do that, use :func:`functools.partial`,
208 e.g.::
209
Carol Willing5b7cbd62018-09-12 17:05:17 -0700210 # will schedule "print("Hello", flush=True)"
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700211 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 better render partial objects in debug and error
216 messages.
Yury Selivanov28b91782018-05-23 13:35:04 -0400217
Victor Stinnerea3183f2013-12-03 01:08:00 +0100218
Victor Stinner45b27ed2014-02-01 02:36:43 +0100219.. _asyncio-delayed-calls:
220
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700221Scheduling delayed callbacks
222^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100223
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700224Event 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 Stinnerea3183f2013-12-03 01:08:00 +0100227
Victor Stinner45b27ed2014-02-01 02:36:43 +0100228
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700229.. method:: loop.call_later(delay, callback, *args, context=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100230
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700231 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 Selivanov7c7605f2018-09-11 09:54:40 -0700234 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 Selivanov7c7605f2018-09-11 09:54:40 -0700237 *callback* will be called exactly once. If two callbacks are
Carol Willing5b7cbd62018-09-12 17:05:17 -0700238 scheduled for exactly the same time, it is undefined which one will
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700239 be called first.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100240
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700241 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 Selivanov7c7605f2018-09-11 09:54:40 -0700245 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
Yury Selivanov28b91782018-05-23 13:35:04 -0400249 .. versionchanged:: 3.7
250 The *context* keyword-only parameter was added. See :pep:`567`
251 for more details.
252
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700253.. method:: loop.call_at(when, callback, *args, context=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100254
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700255 Schedule *callback* to be called at the given absolute timestamp
256 *when* (an int or a float), using the same time reference as
257 :meth:`loop.time`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100258
259 This method's behavior is the same as :meth:`call_later`.
260
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700261 An instance of :class:`asyncio.TimerHandle` is returned which can
262 be used to cancel the callback.
Victor Stinner8464c242014-11-28 13:15:41 +0100263
Yury Selivanov28b91782018-05-23 13:35:04 -0400264 .. versionchanged:: 3.7
265 The *context* keyword-only parameter was added. See :pep:`567`
266 for more details.
267
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700268.. method:: loop.time()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100269
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700270 Return the current time, as a :class:`float` value, according to
271 the event loop's internal monotonic clock.
272
273.. note::
274
275 Timeouts (relative *delay* or absolute *when*) should not
276 exceed one day.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100277
Victor Stinner3e09e322013-12-03 01:22:06 +0100278.. seealso::
279
280 The :func:`asyncio.sleep` function.
281
Victor Stinnerea3183f2013-12-03 01:08:00 +0100282
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700283Creating Futures and Tasks
284^^^^^^^^^^^^^^^^^^^^^^^^^^
Yury Selivanov950204d2016-05-16 16:23:00 -0400285
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700286.. method:: loop.create_future()
Yury Selivanov950204d2016-05-16 16:23:00 -0400287
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700288 Create an :class:`asyncio.Future` object attached to the event loop.
Yury Selivanov950204d2016-05-16 16:23:00 -0400289
Carol Willing5b7cbd62018-09-12 17:05:17 -0700290 This is the preferred way to create Futures in asyncio. This lets
291 third-party event loops provide alternative implementations of
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700292 the Future object (with better performance or instrumentation).
Yury Selivanov950204d2016-05-16 16:23:00 -0400293
294 .. versionadded:: 3.5.2
295
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700296.. method:: loop.create_task(coro, \*, name=None)
Yury Selivanov950204d2016-05-16 16:23:00 -0400297
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700298 Schedule the execution of a :ref:`coroutine`.
299 Return a :class:`Task` object.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200300
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700301 Third-party event loops can use their own subclass of :class:`Task`
302 for interoperability. In this case, the result type is a subclass
303 of :class:`Task`.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200304
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700305 If the *name* argument is provided and not ``None``, it is set as
306 the name of the task using :meth:`Task.set_name`.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200307
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300308 .. versionchanged:: 3.8
309 Added the ``name`` parameter.
310
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700311.. method:: loop.set_task_factory(factory)
Yury Selivanov71854612015-05-11 16:28:27 -0400312
313 Set a task factory that will be used by
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700314 :meth:`loop.create_task`.
Yury Selivanov71854612015-05-11 16:28:27 -0400315
316 If *factory* is ``None`` the default task factory will be set.
317
318 If *factory* is a *callable*, it should have a signature matching
319 ``(loop, coro)``, where *loop* will be a reference to the active
320 event loop, *coro* will be a coroutine object. The callable
321 must return an :class:`asyncio.Future` compatible object.
322
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700323.. method:: loop.get_task_factory()
Yury Selivanov71854612015-05-11 16:28:27 -0400324
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700325 Return a task factory or ``None`` if the default one is in use.
Yury Selivanov71854612015-05-11 16:28:27 -0400326
Victor Stinner530ef2f2014-07-08 12:39:10 +0200327
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700328Opening network connections
329^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100330
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700331.. coroutinemethod:: loop.create_connection(protocol_factory, \
332 host=None, port=None, \*, ssl=None, \
333 family=0, proto=0, flags=0, sock=None, \
334 local_addr=None, server_hostname=None, \
335 ssl_handshake_timeout=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100336
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700337 Open a streaming transport connection to a given
338 address specified by *host* and *port*.
339
340 The socket family can be either :py:data:`~socket.AF_INET` or
341 :py:data:`~socket.AF_INET6` depending on *host* (or the *family*
342 argument, if provided).
343
344 The socket type will be :py:data:`~socket.SOCK_STREAM`.
345
346 *protocol_factory* must be a callable returning an
347 :ref:`asyncio protocol <asyncio-protocol>` implementation.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100348
Yury Selivanov19a44f62017-12-14 20:53:26 -0500349 This method will try to establish the connection in the background.
350 When successful, it returns a ``(transport, protocol)`` pair.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100351
352 The chronological synopsis of the underlying operation is as follows:
353
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700354 #. The connection is established and a :ref:`transport <asyncio-transport>`
355 is created for it.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100356
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700357 #. *protocol_factory* is called without arguments and is expected to
358 return a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100359
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700360 #. The protocol instance is coupled with the transport by calling its
361 :meth:`~BaseProtocol.connection_made` method.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100362
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700363 #. A ``(transport, protocol)`` tuple is returned on success.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100364
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700365 The created transport is an implementation-dependent bidirectional
366 stream.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100367
368 .. note::
369 *protocol_factory* can be any kind of callable, not necessarily
370 a class. For example, if you want to use a pre-created
371 protocol instance, you can pass ``lambda: my_protocol``.
372
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700373 Other arguments:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100374
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700375 * *ssl*: if given and not false, an SSL/TLS transport is created
Victor Stinnerea3183f2013-12-03 01:08:00 +0100376 (by default a plain TCP transport is created). If *ssl* is
377 a :class:`ssl.SSLContext` object, this context is used to create
378 the transport; if *ssl* is :const:`True`, a context with some
379 unspecified default settings is used.
380
Berker Peksag9c1dba22014-09-28 00:00:58 +0300381 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100382
Victor Stinnerea3183f2013-12-03 01:08:00 +0100383 * *server_hostname*, is only for use together with *ssl*,
384 and sets or overrides the hostname that the target server's certificate
385 will be matched against. By default the value of the *host* argument
386 is used. If *host* is empty, there is no default and you must pass a
387 value for *server_hostname*. If *server_hostname* is an empty
388 string, hostname matching is disabled (which is a serious security
389 risk, allowing for man-in-the-middle-attacks).
390
391 * *family*, *proto*, *flags* are the optional address family, protocol
392 and flags to be passed through to getaddrinfo() for *host* resolution.
393 If given, these should all be integers from the corresponding
394 :mod:`socket` module constants.
395
396 * *sock*, if given, should be an existing, already connected
397 :class:`socket.socket` object to be used by the transport.
398 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
399 and *local_addr* should be specified.
400
401 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
402 to bind the socket to locally. The *local_host* and *local_port*
Carol Willing5b7cbd62018-09-12 17:05:17 -0700403 are looked up using ``getaddrinfo()``, similarly to *host* and *port*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100404
Neil Aspinallf7686c12017-12-19 19:45:42 +0000405 * *ssl_handshake_timeout* is (for an SSL connection) the time in seconds
406 to wait for the SSL handshake to complete before aborting the connection.
Yury Selivanov96026432018-06-04 11:32:35 -0400407 ``60.0`` seconds if ``None`` (default).
Neil Aspinallf7686c12017-12-19 19:45:42 +0000408
409 .. versionadded:: 3.7
410
411 The *ssl_handshake_timeout* parameter.
412
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700413 .. versionchanged:: 3.6
414
415 The socket option :py:data:`~socket.TCP_NODELAY` is set by default
416 for all TCP connections.
417
Victor Stinner60208a12015-09-15 22:41:52 +0200418 .. versionchanged:: 3.5
419
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700420 Added support for SSL/TLS for :class:`ProactorEventLoop`.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200421
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100422 .. seealso::
423
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700424 The :func:`open_connection` function is a high-level alternative
425 API. It returns a pair of (:class:`StreamReader`, :class:`StreamWriter`)
426 that can be used directly in async/await code.
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100427
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700428.. coroutinemethod:: loop.create_datagram_endpoint(protocol_factory, \
429 local_addr=None, remote_addr=None, \*, \
430 family=0, proto=0, flags=0, \
431 reuse_address=None, reuse_port=None, \
432 allow_broadcast=None, sock=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100433
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700434 Create a datagram connection.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100435
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700436 The socket family can be either :py:data:`~socket.AF_INET`,
437 :py:data:`~socket.AF_INET6`, or :py:data:`~socket.AF_UNIX`,
438 depending on *host* (or the *family* argument, if provided).
Victor Stinnera6919aa2014-02-19 13:32:34 +0100439
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700440 The socket type will be :py:data:`~socket.SOCK_DGRAM`.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100441
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700442 *protocol_factory* must be a callable returning a
443 :ref:`protocol <asyncio-protocol>` implementation.
444
445 A tuple of ``(transport, protocol)`` is returned on success.
446
447 Other arguments:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700448
449 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
450 to bind the socket to locally. The *local_host* and *local_port*
451 are looked up using :meth:`getaddrinfo`.
452
453 * *remote_addr*, if given, is a ``(remote_host, remote_port)`` tuple used
454 to connect the socket to a remote address. The *remote_host* and
455 *remote_port* are looked up using :meth:`getaddrinfo`.
456
457 * *family*, *proto*, *flags* are the optional address family, protocol
458 and flags to be passed through to :meth:`getaddrinfo` for *host*
459 resolution. If given, these should all be integers from the
460 corresponding :mod:`socket` module constants.
461
462 * *reuse_address* tells the kernel to reuse a local socket in
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700463 ``TIME_WAIT`` state, without waiting for its natural timeout to
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300464 expire. If not specified will automatically be set to ``True`` on
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700465 UNIX.
466
467 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
468 same port as other existing endpoints are bound to, so long as they all
469 set this flag when being created. This option is not supported on Windows
470 and some UNIX's. If the :py:data:`~socket.SO_REUSEPORT` constant is not
471 defined then this capability is unsupported.
472
473 * *allow_broadcast* tells the kernel to allow this endpoint to send
474 messages to the broadcast address.
475
476 * *sock* can optionally be specified in order to use a preexisting,
477 already connected, :class:`socket.socket` object to be used by the
478 transport. If specified, *local_addr* and *remote_addr* should be omitted
479 (must be :const:`None`).
Victor Stinnera6919aa2014-02-19 13:32:34 +0100480
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200481 On Windows with :class:`ProactorEventLoop`, this method is not supported.
482
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200483 See :ref:`UDP echo client protocol <asyncio-udp-echo-client-protocol>` and
484 :ref:`UDP echo server protocol <asyncio-udp-echo-server-protocol>` examples.
485
Romuald Brunet0ded5802018-05-14 18:22:00 +0200486 .. versionchanged:: 3.4.4
487 The *family*, *proto*, *flags*, *reuse_address*, *reuse_port,
488 *allow_broadcast*, and *sock* parameters were added.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100489
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700490.. coroutinemethod:: loop.create_unix_connection(protocol_factory, \
491 path=None, \*, ssl=None, sock=None, \
492 server_hostname=None, ssl_handshake_timeout=None)
Victor Stinnera6919aa2014-02-19 13:32:34 +0100493
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700494 Create UNIX connection.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100495
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700496 The socket family will be :py:data:`~socket.AF_UNIX`; socket
497 type will be :py:data:`~socket.SOCK_STREAM`.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100498
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700499 A tuple of ``(transport, protocol)`` is returned on success.
Guido van Rossum9e80eeb2016-11-03 14:17:25 -0700500
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700501 *path* is the name of a UNIX domain socket and is required,
502 unless a *sock* parameter is specified. Abstract UNIX sockets,
503 :class:`str`, :class:`bytes`, and :class:`~pathlib.Path` paths are
504 supported.
505
506 See the documentation of the :meth:`loop.create_connection` method
507 for information about arguments to this method.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100508
509 Availability: UNIX.
510
Neil Aspinallf7686c12017-12-19 19:45:42 +0000511 .. versionadded:: 3.7
512
513 The *ssl_handshake_timeout* parameter.
514
Yury Selivanov423fd362017-11-20 17:26:28 -0500515 .. versionchanged:: 3.7
516
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400517 The *path* parameter can now be a :term:`path-like object`.
Yury Selivanov423fd362017-11-20 17:26:28 -0500518
Victor Stinnera6919aa2014-02-19 13:32:34 +0100519
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700520Creating network servers
521^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100522
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700523.. coroutinemethod:: loop.create_server(protocol_factory, \
524 host=None, port=None, \*, \
525 family=socket.AF_UNSPEC, \
526 flags=socket.AI_PASSIVE, \
527 sock=None, backlog=100, ssl=None, \
528 reuse_address=None, reuse_port=None, \
529 ssl_handshake_timeout=None, start_serving=True)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100530
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700531 Create a TCP server (socket type :data:`~socket.SOCK_STREAM`) listening
532 on the *host* and *port* address.
Victor Stinner33f6abe2014-10-12 20:36:04 +0200533
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700534 Returns a :class:`Server` object.
Victor Stinner33f6abe2014-10-12 20:36:04 +0200535
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700536 Arguments:
Victor Stinner33f6abe2014-10-12 20:36:04 +0200537
Carol Willing5b7cbd62018-09-12 17:05:17 -0700538 * The *host* parameter can be set to several types which determine behavior:
539 - If *host* is a string, the TCP server is bound to *host* and *port*.
540 - if *host* is a sequence of strings, the TCP server is bound to all
541 hosts of the sequence.
542 - If *host* is an empty string or ``None``, all interfaces are
543 assumed and a list of multiple sockets will be returned (most likely
544 one for IPv4 and another one for IPv6).
Victor Stinner33f6abe2014-10-12 20:36:04 +0200545
546 * *family* can be set to either :data:`socket.AF_INET` or
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700547 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6.
Carol Willing5b7cbd62018-09-12 17:05:17 -0700548 If not set, the *family* will be determined from host name
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700549 (defaults to :data:`~socket.AF_UNSPEC`).
Victor Stinner33f6abe2014-10-12 20:36:04 +0200550
551 * *flags* is a bitmask for :meth:`getaddrinfo`.
552
553 * *sock* can optionally be specified in order to use a preexisting
554 socket object. If specified, *host* and *port* should be omitted (must be
555 :const:`None`).
556
557 * *backlog* is the maximum number of queued connections passed to
558 :meth:`~socket.socket.listen` (defaults to 100).
559
560 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the
561 accepted connections.
562
563 * *reuse_address* tells the kernel to reuse a local socket in
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700564 ``TIME_WAIT`` state, without waiting for its natural timeout to
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300565 expire. If not specified will automatically be set to ``True`` on
Victor Stinner33f6abe2014-10-12 20:36:04 +0200566 UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100567
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700568 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
569 same port as other existing endpoints are bound to, so long as they all
570 set this flag when being created. This option is not supported on
571 Windows.
572
Neil Aspinallf7686c12017-12-19 19:45:42 +0000573 * *ssl_handshake_timeout* is (for an SSL server) the time in seconds to wait
574 for the SSL handshake to complete before aborting the connection.
Yury Selivanov96026432018-06-04 11:32:35 -0400575 ``60.0`` seconds if ``None`` (default).
Neil Aspinallf7686c12017-12-19 19:45:42 +0000576
Yury Selivanovc9070d02018-01-25 18:08:09 -0500577 * *start_serving* set to ``True`` (the default) causes the created server
578 to start accepting connections immediately. When set to ``False``,
579 the user should await on :meth:`Server.start_serving` or
580 :meth:`Server.serve_forever` to make the server to start accepting
581 connections.
582
Neil Aspinallf7686c12017-12-19 19:45:42 +0000583 .. versionadded:: 3.7
584
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700585 Added *ssl_handshake_timeout* and *start_serving* parameters.
586
587 .. versionchanged:: 3.6
588
589 The socket option :py:data:`~socket.TCP_NODELAY` is set by default
590 for all TCP connections.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000591
Victor Stinner60208a12015-09-15 22:41:52 +0200592 .. versionchanged:: 3.5
593
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700594 Added support for SSL/TLS on Windows with
595 :class:`ProactorEventLoop`.
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100596
Victor Stinner7b58a2b2015-09-21 18:41:05 +0200597 .. versionchanged:: 3.5.1
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200598
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700599 The *host* parameter can be a sequence of strings.
600
601 .. seealso::
602
603 The :func:`start_server` function is a higher-level alternative API
604 that returns a pair of :class:`StreamReader` and :class:`StreamWriter`
605 that can be used in an async/await code.
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200606
Victor Stinnerea3183f2013-12-03 01:08:00 +0100607
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700608.. coroutinemethod:: loop.create_unix_server(protocol_factory, path=None, \
609 \*, sock=None, backlog=100, ssl=None, \
610 ssl_handshake_timeout=None, start_serving=True)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100611
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700612 Similar to :meth:`loop.create_server` but works with the
613 :py:data:`~socket.AF_UNIX` socket family.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100614
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700615 *path* is the name of a UNIX domain socket, and is required,
616 unless a *sock* argument is provided. Abstract UNIX sockets,
617 :class:`str`, :class:`bytes`, and :class:`~pathlib.Path` paths
618 are supported.
Yury Selivanov423fd362017-11-20 17:26:28 -0500619
Victor Stinnera6919aa2014-02-19 13:32:34 +0100620 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100621
Neil Aspinallf7686c12017-12-19 19:45:42 +0000622 .. versionadded:: 3.7
623
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400624 The *ssl_handshake_timeout* and *start_serving* parameters.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000625
Yury Selivanov423fd362017-11-20 17:26:28 -0500626 .. versionchanged:: 3.7
627
628 The *path* parameter can now be a :class:`~pathlib.Path` object.
629
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700630.. coroutinemethod:: loop.connect_accepted_socket(protocol_factory, \
631 sock, \*, ssl=None, ssl_handshake_timeout=None)
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500632
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700633 Wrap an already accepted connection into a transport/protocol pair.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500634
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700635 This method can be used by servers that accept connections outside
636 of asyncio but that use asyncio to handle them.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500637
638 Parameters:
639
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700640 * *sock* is a preexisting socket object returned from
641 :meth:`socket.accept <socket.socket.accept>`.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500642
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700643 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over
644 the accepted connections.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500645
Neil Aspinallf7686c12017-12-19 19:45:42 +0000646 * *ssl_handshake_timeout* is (for an SSL connection) the time in seconds to
647 wait for the SSL handshake to complete before aborting the connection.
Yury Selivanov96026432018-06-04 11:32:35 -0400648 ``60.0`` seconds if ``None`` (default).
Neil Aspinallf7686c12017-12-19 19:45:42 +0000649
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700650 Returns a ``(transport, protocol)`` pair.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100651
Neil Aspinallf7686c12017-12-19 19:45:42 +0000652 .. versionadded:: 3.7
653
654 The *ssl_handshake_timeout* parameter.
655
AraHaan431665b2017-11-21 11:06:26 -0500656 .. versionadded:: 3.5.3
657
658
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700659Transferring files
660^^^^^^^^^^^^^^^^^^
Andrew Svetlov7c684072018-01-27 21:22:47 +0200661
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700662.. coroutinemethod:: loop.sendfile(transport, file, \
663 offset=0, count=None, *, fallback=True)
Andrew Svetlov7c684072018-01-27 21:22:47 +0200664
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700665 Send a *file* over a *transport*. Return the total number of bytes
666 sent.
Andrew Svetlov7c684072018-01-27 21:22:47 +0200667
668 The method uses high-performance :meth:`os.sendfile` if available.
669
670 *file* must be a regular file object opened in binary mode.
671
672 *offset* tells from where to start reading the file. If specified,
673 *count* is the total number of bytes to transmit as opposed to
674 sending the file until EOF is reached. File position is updated on
675 return or also in case of error in which case :meth:`file.tell()
676 <io.IOBase.tell>` can be used to figure out the number of bytes
677 which were sent.
678
679 *fallback* set to ``True`` makes asyncio to manually read and send
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700680 the file when the platform does not support the sendfile system call
Andrew Svetlov7c684072018-01-27 21:22:47 +0200681 (e.g. Windows or SSL socket on Unix).
682
683 Raise :exc:`SendfileNotAvailableError` if the system does not support
684 *sendfile* syscall and *fallback* is ``False``.
685
686 .. versionadded:: 3.7
687
688
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500689TLS Upgrade
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700690^^^^^^^^^^^
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500691
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700692.. coroutinemethod:: loop.start_tls(transport, protocol, \
693 sslcontext, \*, server_side=False, \
694 server_hostname=None, ssl_handshake_timeout=None)
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500695
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700696 Upgrade an existing transport-based connection to TLS.
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500697
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700698 Return a new transport instance, that the *protocol* must start using
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500699 immediately after the *await*. The *transport* instance passed to
700 the *start_tls* method should never be used again.
701
702 Parameters:
703
704 * *transport* and *protocol* instances that methods like
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700705 :meth:`~loop.create_server` and
706 :meth:`~loop.create_connection` return.
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500707
708 * *sslcontext*: a configured instance of :class:`~ssl.SSLContext`.
709
710 * *server_side* pass ``True`` when a server-side connection is being
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700711 upgraded (like the one created by :meth:`~loop.create_server`).
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500712
713 * *server_hostname*: sets or overrides the host name that the target
714 server's certificate will be matched against.
715
716 * *ssl_handshake_timeout* is (for an SSL connection) the time in seconds to
717 wait for the SSL handshake to complete before aborting the connection.
Yury Selivanov96026432018-06-04 11:32:35 -0400718 ``60.0`` seconds if ``None`` (default).
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500719
720 .. versionadded:: 3.7
721
722
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700723Watching file descriptors
724^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerc1567df2014-02-08 23:22:58 +0100725
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700726.. method:: loop.add_reader(fd, callback, \*args)
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200727
Carol Willing5b7cbd62018-09-12 17:05:17 -0700728 Start watching the file descriptor *fd* for read availability and
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700729 call the *callback* with specified arguments.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200730
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700731.. method:: loop.remove_reader(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100732
Carol Willing5b7cbd62018-09-12 17:05:17 -0700733 Stop watching the file descriptor *fd* for read availability.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100734
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700735.. method:: loop.add_writer(fd, callback, \*args)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100736
Carol Willing5b7cbd62018-09-12 17:05:17 -0700737 Start watching the file descriptor *fd* for write availability and then
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700738 call the *callback* with specified arguments.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100739
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700740 Use :func:`functools.partial` :ref:`to pass keywords
741 <asyncio-pass-keywords>` to *func*.
Victor Stinner8464c242014-11-28 13:15:41 +0100742
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700743.. method:: loop.remove_writer(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100744
Carol Willing5b7cbd62018-09-12 17:05:17 -0700745 Stop watching the file descriptor *fd* for write availability.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100746
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700747See also :ref:`Platform Support <asyncio-platform-support>` section
748for some limitations of these methods.
Victor Stinner04e6df32014-10-11 16:16:27 +0200749
Victor Stinnerc1567df2014-02-08 23:22:58 +0100750
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700751Working with socket objects directly
752^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerc1567df2014-02-08 23:22:58 +0100753
Carol Willing5b7cbd62018-09-12 17:05:17 -0700754In general, protocol implementations that use transport-based APIs
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700755such as :meth:`loop.create_connection` and :meth:`loop.create_server`
756are faster than implementations that work with sockets directly.
Carol Willing5b7cbd62018-09-12 17:05:17 -0700757However, there are some use cases when performance is not critical, and
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700758working with :class:`~socket.socket` objects directly is more
759convenient.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100760
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700761.. coroutinemethod:: loop.sock_recv(sock, nbytes)
Yury Selivanov55c50842016-06-08 12:48:15 -0400762
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700763 Receive data. Asynchronous version of
764 :meth:`socket.recv() <socket.socket.recv>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100765
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700766 The received data is returned as a bytes object. The maximum amount
767 of data to be received is specified by the *nbytes* argument.
768
769 The socket *sock* must be non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200770
Yury Selivanov19a44f62017-12-14 20:53:26 -0500771 .. versionchanged:: 3.7
Carol Willing5b7cbd62018-09-12 17:05:17 -0700772 Even though this method was always documented as a coroutine
773 method, releases before Python 3.7 returned a :class:`Future`.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700774 Since Python 3.7 this is an ``async def`` method.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100775
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700776.. coroutinemethod:: loop.sock_recv_into(sock, buf)
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200777
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700778 Receive data into a buffer. Modeled after the blocking
779 :meth:`socket.recv_into() <socket.socket.recv_into>` method.
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200780
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700781 Return the number of bytes written to the buffer.
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200782
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700783 The socket *sock* must be non-blocking.
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200784
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200785 .. versionadded:: 3.7
786
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700787.. coroutinemethod:: loop.sock_sendall(sock, data)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100788
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700789 Send data to the socket. Asynchronous version of
790 :meth:`socket.sendall() <socket.socket.sendall>`.
Yury Selivanov55c50842016-06-08 12:48:15 -0400791
Carol Willing5b7cbd62018-09-12 17:05:17 -0700792 This method continues to send data from *data* to the socket until either
793 all data in *data* has been sent or an error occurs. ``None`` is returned
794 on success. On error, an exception is raised. Additionally, there is no way
795 to determine how much data, if any, was successfully processed by the
796 receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100797
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700798 The socket *sock* must be non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200799
Yury Selivanov19a44f62017-12-14 20:53:26 -0500800 .. versionchanged:: 3.7
801 Even though the method was always documented as a coroutine
802 method, before Python 3.7 it returned an :class:`Future`.
803 Since Python 3.7, this is an ``async def`` method.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100804
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700805.. coroutinemethod:: loop.sock_connect(sock, address)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100806
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700807 Connect to a remote socket at *address*.
Victor Stinner1b0580b2014-02-13 09:24:37 +0100808
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700809 Asynchronous version of :meth:`socket.connect() <socket.socket.connect>`.
810
811 The socket *sock* must be non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200812
Yury Selivanov55c50842016-06-08 12:48:15 -0400813 .. versionchanged:: 3.5.2
814 ``address`` no longer needs to be resolved. ``sock_connect``
815 will try to check if the *address* is already resolved by calling
816 :func:`socket.inet_pton`. If not,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700817 :meth:`loop.getaddrinfo` will be used to resolve the
Yury Selivanov55c50842016-06-08 12:48:15 -0400818 *address*.
819
Victor Stinnerc1567df2014-02-08 23:22:58 +0100820 .. seealso::
821
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700822 :meth:`loop.create_connection`
Yury Selivanov55c50842016-06-08 12:48:15 -0400823 and :func:`asyncio.open_connection() <open_connection>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100824
825
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700826.. coroutinemethod:: loop.sock_accept(sock)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100827
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700828 Accept a connection. Modeled after the blocking
829 :meth:`socket.accept() <socket.socket.accept>` method.
Yury Selivanov55c50842016-06-08 12:48:15 -0400830
831 The socket must be bound to an address and listening
Victor Stinnerc1567df2014-02-08 23:22:58 +0100832 for connections. The return value is a pair ``(conn, address)`` where *conn*
833 is a *new* socket object usable to send and receive data on the connection,
834 and *address* is the address bound to the socket on the other end of the
835 connection.
836
Victor Stinnerec2ce092014-07-29 23:12:22 +0200837 The socket *sock* must be non-blocking.
838
Yury Selivanov19a44f62017-12-14 20:53:26 -0500839 .. versionchanged:: 3.7
840 Even though the method was always documented as a coroutine
841 method, before Python 3.7 it returned a :class:`Future`.
842 Since Python 3.7, this is an ``async def`` method.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100843
844 .. seealso::
845
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700846 :meth:`loop.create_server` and :func:`start_server`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100847
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700848.. coroutinemethod:: loop.sock_sendfile(sock, file, offset=0, count=None, \
849 \*, fallback=True)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200850
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700851 Send a file using high-performance :mod:`os.sendfile` if possible.
852 Return the total number of bytes which were sent.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200853
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700854 Asynchronous version of :meth:`socket.sendfile() <socket.socket.sendfile>`.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200855
856 *sock* must be non-blocking :class:`~socket.socket` of
857 :const:`socket.SOCK_STREAM` type.
858
859 *file* must be a regular file object opened in binary mode.
860
861 *offset* tells from where to start reading the file. If specified,
862 *count* is the total number of bytes to transmit as opposed to
863 sending the file until EOF is reached. File position is updated on
864 return or also in case of error in which case :meth:`file.tell()
865 <io.IOBase.tell>` can be used to figure out the number of bytes
866 which were sent.
867
Carol Willing5b7cbd62018-09-12 17:05:17 -0700868 *fallback*, when set to ``True``, makes asyncio manually read and send
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200869 the file when the platform does not support the sendfile syscall
870 (e.g. Windows or SSL socket on Unix).
871
Andrew Svetlov7464e872018-01-19 20:04:29 +0200872 Raise :exc:`SendfileNotAvailableError` if the system does not support
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200873 *sendfile* syscall and *fallback* is ``False``.
874
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700875 The socket *sock* must be non-blocking.
876
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200877 .. versionadded:: 3.7
878
Victor Stinnerc1567df2014-02-08 23:22:58 +0100879
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700880DNS
881^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100882
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700883.. coroutinemethod:: loop.getaddrinfo(host, port, \*, family=0, \
884 type=0, proto=0, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100885
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700886 Asynchronous version of :meth:`socket.getaddrinfo`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100887
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700888.. coroutinemethod:: loop.getnameinfo(sockaddr, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100889
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700890 Asynchronous version of :meth:`socket.getnameinfo`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100891
Yury Selivanovbec23722018-01-28 14:09:40 -0500892.. versionchanged:: 3.7
893 Both *getaddrinfo* and *getnameinfo* methods were always documented
894 to return a coroutine, but prior to Python 3.7 they were, in fact,
895 returning :class:`asyncio.Future` objects. Starting with Python 3.7
896 both methods are coroutines.
897
Victor Stinnerea3183f2013-12-03 01:08:00 +0100898
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700899Working with pipes
900^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100901
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700902.. coroutinemethod:: loop.connect_read_pipe(protocol_factory, pipe)
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200903
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700904 Register a read-pipe in the event loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100905
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700906 *protocol_factory* must be a callable returning an
907 :ref:`asyncio protocol <asyncio-protocol>` implementation.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100908
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700909 *pipe* is a :term:`file-like object <file object>`.
910
911 Return pair ``(transport, protocol)``, where *transport* supports
912 the :class:`ReadTransport` interface.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100913
Victor Stinnerd84fd732014-08-26 01:01:59 +0200914 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
915 non-blocking mode.
916
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700917.. coroutinemethod:: loop.connect_write_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100918
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700919 Register a write-pipe in the event loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100920
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700921 *protocol_factory* must be a callable returning an
922 :ref:`asyncio protocol <asyncio-protocol>` implementation.
923
924 *pipe* is :term:`file-like object <file object>`.
925
Victor Stinner2cef3002014-10-23 22:38:46 +0200926 Return pair ``(transport, protocol)``, where *transport* supports
Victor Stinnerea3183f2013-12-03 01:08:00 +0100927 :class:`WriteTransport` interface.
928
Victor Stinnerd84fd732014-08-26 01:01:59 +0200929 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
930 non-blocking mode.
931
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700932.. note::
933
934 :class:`SelectorEventLoop` does not support the above methods on
Carol Willing5b7cbd62018-09-12 17:05:17 -0700935 Windows. Use :class:`ProactorEventLoop` instead for Windows.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700936
Victor Stinner08444382014-02-02 22:43:39 +0100937.. seealso::
938
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700939 The :meth:`loop.subprocess_exec` and
940 :meth:`loop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100941
Victor Stinnerea3183f2013-12-03 01:08:00 +0100942
Victor Stinner8b863482014-01-27 10:07:50 +0100943UNIX signals
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700944^^^^^^^^^^^^
Victor Stinner8b863482014-01-27 10:07:50 +0100945
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700946.. method:: loop.add_signal_handler(signum, callback, \*args)
Victor Stinner8b863482014-01-27 10:07:50 +0100947
948 Add a handler for a signal.
949
950 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
951 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
952
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700953 Use :func:`functools.partial` :ref:`to pass keywords
954 <asyncio-pass-keywords>` to *func*.
Victor Stinner8464c242014-11-28 13:15:41 +0100955
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700956.. method:: loop.remove_signal_handler(sig)
Victor Stinner8b863482014-01-27 10:07:50 +0100957
958 Remove a handler for a signal.
959
960 Return ``True`` if a signal handler was removed, ``False`` if not.
961
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700962Availability: UNIX.
963
Victor Stinner8b863482014-01-27 10:07:50 +0100964.. seealso::
965
966 The :mod:`signal` module.
967
968
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700969Executing code in thread or process pools
970^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100971
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700972.. method:: loop.run_in_executor(executor, func, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100973
Andrew Svetlov1c62b522015-10-01 09:48:08 +0300974 Arrange for a *func* to be called in the specified executor.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100975
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700976 The *executor* argument should be an :class:`concurrent.futures.Executor`
Larry Hastings3732ed22014-03-15 21:13:56 -0700977 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100978
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700979 Use :func:`functools.partial` :ref:`to pass keywords
980 <asyncio-pass-keywords>` to *func*.
Victor Stinner8464c242014-11-28 13:15:41 +0100981
Yury Selivanovbec23722018-01-28 14:09:40 -0500982 This method returns a :class:`asyncio.Future` object.
983
Yury Selivanove8a60452016-10-21 17:40:42 -0400984 .. versionchanged:: 3.5.3
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700985 :meth:`loop.run_in_executor` no longer configures the
Yury Selivanove8a60452016-10-21 17:40:42 -0400986 ``max_workers`` of the thread pool executor it creates, instead
987 leaving it up to the thread pool executor
988 (:class:`~concurrent.futures.ThreadPoolExecutor`) to set the
989 default.
990
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700991.. method:: loop.set_default_executor(executor)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100992
Elvis Pranskevichus22d25082018-07-30 11:42:43 +0100993 Set *executor* as the default executor used by :meth:`run_in_executor`.
994 *executor* should be an instance of
995 :class:`~concurrent.futures.ThreadPoolExecutor`.
996
997 .. deprecated:: 3.8
998 Using an executor that is not an instance of
999 :class:`~concurrent.futures.ThreadPoolExecutor` is deprecated and
1000 will trigger an error in Python 3.9.
Victor Stinnerea3183f2013-12-03 01:08:00 +01001001
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001002 *executor* must be an instance of
1003 :class:`concurrent.futures.ThreadPoolExecutor`.
1004
Victor Stinnerea3183f2013-12-03 01:08:00 +01001005
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001006Error Handling API
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001007^^^^^^^^^^^^^^^^^^
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001008
Martin Panterc04fb562016-02-10 05:44:01 +00001009Allows customizing how exceptions are handled in the event loop.
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001010
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001011.. method:: loop.set_exception_handler(handler)
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001012
1013 Set *handler* as the new event loop exception handler.
1014
1015 If *handler* is ``None``, the default exception handler will
1016 be set.
1017
1018 If *handler* is a callable object, it should have a
1019 matching signature to ``(loop, context)``, where ``loop``
1020 will be a reference to the active event loop, ``context``
1021 will be a ``dict`` object (see :meth:`call_exception_handler`
1022 documentation for details about context).
1023
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001024.. method:: loop.get_exception_handler()
Yury Selivanov950204d2016-05-16 16:23:00 -04001025
1026 Return the exception handler, or ``None`` if the default one
1027 is in use.
1028
1029 .. versionadded:: 3.5.2
1030
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001031.. method:: loop.default_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001032
1033 Default exception handler.
1034
1035 This is called when an exception occurs and no exception
Carol Willing5b7cbd62018-09-12 17:05:17 -07001036 handler is set. This can be called by a custom exception
1037 handler that wants to defer to the default handler behavior.
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001038
1039 *context* parameter has the same meaning as in
1040 :meth:`call_exception_handler`.
1041
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001042.. method:: loop.call_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001043
1044 Call the current event loop exception handler.
1045
1046 *context* is a ``dict`` object containing the following keys
1047 (new keys may be introduced later):
1048
1049 * 'message': Error message;
1050 * 'exception' (optional): Exception object;
1051 * 'future' (optional): :class:`asyncio.Future` instance;
1052 * 'handle' (optional): :class:`asyncio.Handle` instance;
1053 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
1054 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
1055 * 'socket' (optional): :class:`socket.socket` instance.
1056
1057 .. note::
1058
Carol Willing5b7cbd62018-09-12 17:05:17 -07001059 This method should not be overloaded in subclassed
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001060 event loops. For any custom exception handling, use
1061 :meth:`set_exception_handler()` method.
1062
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001063Enabling debug mode
1064^^^^^^^^^^^^^^^^^^^
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001065
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001066.. method:: loop.get_debug()
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001067
Victor Stinner7b7120e2014-06-23 00:12:14 +02001068 Get the debug mode (:class:`bool`) of the event loop.
1069
1070 The default value is ``True`` if the environment variable
1071 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
1072 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001073
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001074.. method:: loop.set_debug(enabled: bool)
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001075
1076 Set the debug mode of the event loop.
1077
Yury Selivanov805e27e2018-09-14 16:57:11 -07001078 .. versionchanged:: 3.7
1079
1080 The new ``-X dev`` command line option can now also be used
1081 to enable the debug mode.
1082
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001083.. seealso::
1084
Victor Stinner62511fd2014-06-23 00:36:11 +02001085 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001086
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001087
1088Running Subprocesses
1089^^^^^^^^^^^^^^^^^^^^
1090
1091Methods described in this subsections are low-level. In an
1092async/await code consider using high-level convenient
1093:func:`asyncio.create_subprocess_shell` and
1094:func:`asyncio.create_subprocess_exec` functions instead.
1095
1096.. note::
1097
1098 The default event loop that asyncio is pre-configured
1099 to use on **Windows** does not support subprocesses.
1100 See :ref:`Subprocess Support on Windows <asyncio-windows-subprocess>`
1101 for details.
1102
1103.. coroutinemethod:: loop.subprocess_exec(protocol_factory, \*args, \
1104 stdin=subprocess.PIPE, stdout=subprocess.PIPE, \
1105 stderr=subprocess.PIPE, \*\*kwargs)
1106
1107 Create a subprocess from one or more string arguments specified by
1108 *args*.
1109
1110 *args* must be a list of strings represented by:
1111
1112 * :class:`str`;
1113 * or :class:`bytes`, encoded to the
1114 :ref:`filesystem encoding <filesystem-encoding>`.
1115
1116 The first string specifies the program to execute,
Carol Willing5b7cbd62018-09-12 17:05:17 -07001117 and the remaining strings specify the arguments. Together, string
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001118 arguments form the ``argv`` of the program.
1119
1120 This is similar to the standard library :class:`subprocess.Popen`
1121 class called with ``shell=False`` and the list of strings passed as
1122 the first argument; however, where :class:`~subprocess.Popen` takes
1123 a single argument which is list of strings, *subprocess_exec*
1124 takes multiple string arguments.
1125
1126 The *protocol_factory* must instantiate a subclass of the
1127 :class:`asyncio.SubprocessProtocol` class.
1128
1129 Other parameters:
1130
1131 * *stdin*: either a file-like object representing a pipe to be
1132 connected to the subprocess's standard input stream using
1133 :meth:`~loop.connect_write_pipe`, or the
1134 :const:`subprocess.PIPE` constant (default). By default a new
1135 pipe will be created and connected.
1136
1137 * *stdout*: either a file-like object representing the pipe to be
1138 connected to the subprocess's standard output stream using
1139 :meth:`~loop.connect_read_pipe`, or the
1140 :const:`subprocess.PIPE` constant (default). By default a new pipe
1141 will be created and connected.
1142
1143 * *stderr*: either a file-like object representing the pipe to be
1144 connected to the subprocess's standard error stream using
1145 :meth:`~loop.connect_read_pipe`, or one of
1146 :const:`subprocess.PIPE` (default) or :const:`subprocess.STDOUT`
1147 constants.
1148
1149 By default a new pipe will be created and connected. When
1150 :const:`subprocess.STDOUT` is specified, the subprocess' standard
1151 error stream will be connected to the same pipe as the standard
1152 output stream.
1153
1154 * All other keyword arguments are passed to :class:`subprocess.Popen`
1155 without interpretation, except for *bufsize*, *universal_newlines*
1156 and *shell*, which should not be specified at all.
1157
1158 See the constructor of the :class:`subprocess.Popen` class
1159 for documentation on other arguments.
1160
1161 Returns a pair of ``(transport, protocol)``, where *transport*
1162 conforms to the :class:`asyncio.SubprocessTransport` base class.
1163
1164.. coroutinemethod:: loop.subprocess_shell(protocol_factory, cmd, \*, \
1165 stdin=subprocess.PIPE, stdout=subprocess.PIPE, \
1166 stderr=subprocess.PIPE, \*\*kwargs)
1167
1168 Create a subprocess from *cmd*, which can be a :class:`str` or a
1169 :class:`bytes` string encoded to the
1170 :ref:`filesystem encoding <filesystem-encoding>`,
1171 using the platform's "shell" syntax.
1172
1173 This is similar to the standard library :class:`subprocess.Popen`
1174 class called with ``shell=True``.
1175
1176 The *protocol_factory* must instantiate a subclass of the
1177 :class:`SubprocessProtocol` class.
1178
1179 See :meth:`~loop.subprocess_exec` for more details about
1180 the remaining arguments.
1181
1182 Returns a pair of ``(transport, protocol)``, where *transport*
1183 conforms to the :class:`SubprocessTransport` base class.
1184
1185.. note::
1186 It is the application's responsibility to ensure that all whitespace
1187 and metacharacters are quoted appropriately to avoid `shell injection
1188 <https://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_
1189 vulnerabilities. The :func:`shlex.quote` function can be used to
1190 properly escape whitespace and shell metacharacters in strings that
1191 are going to be used to construct shell commands.
1192
1193
1194Callback Handles
1195================
1196
1197.. class:: Handle
1198
1199 A callback wrapper object returned by :meth:`loop.call_soon`,
1200 :meth:`loop.call_soon_threadsafe`.
1201
1202 .. method:: cancel()
1203
1204 Cancel the call. If the callback is already canceled or executed,
1205 this method has no effect.
1206
1207 .. method:: cancelled()
1208
1209 Return ``True`` if the call was cancelled.
1210
1211 .. versionadded:: 3.7
1212
1213.. class:: TimerHandle
1214
1215 A callback wrapper object returned by :meth:`loop.call_later`,
1216 and :meth:`loop.call_at`.
1217
1218 The class is inherited from :class:`Handle`.
1219
1220 .. method:: when()
1221
1222 Return a scheduled callback time as :class:`float` seconds.
1223
1224 The time is an absolute timestamp, using the same time
1225 reference as :meth:`loop.time`.
1226
1227 .. versionadded:: 3.7
1228
1229
1230Server Objects
1231==============
1232
1233Server objects are created by :meth:`loop.create_server`,
1234:meth:`loop.create_unix_server`, :func:`start_server`,
1235and :func:`start_unix_server` functions.
1236
1237Do not instantiate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +01001238
Victor Stinner8ebeb032014-07-11 23:47:40 +02001239.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +01001240
Yury Selivanovc9070d02018-01-25 18:08:09 -05001241 *Server* objects are asynchronous context managers. When used in an
1242 ``async with`` statement, it's guaranteed that the Server object is
1243 closed and not accepting new connections when the ``async with``
1244 statement is completed::
1245
1246 srv = await loop.create_server(...)
1247
1248 async with srv:
1249 # some code
1250
Carol Willing5b7cbd62018-09-12 17:05:17 -07001251 # At this point, srv is closed and no longer accepts new connections.
Yury Selivanovc9070d02018-01-25 18:08:09 -05001252
1253
1254 .. versionchanged:: 3.7
1255 Server object is an asynchronous context manager since Python 3.7.
Victor Stinner8c462c52014-01-24 18:11:43 +01001256
1257 .. method:: close()
1258
Victor Stinner4bfb14a2014-07-12 03:20:24 +02001259 Stop serving: close listening sockets and set the :attr:`sockets`
1260 attribute to ``None``.
1261
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001262 The sockets that represent existing incoming client connections
1263 are left open.
Victor Stinner8ebeb032014-07-11 23:47:40 +02001264
Berker Peksag49c9edf2016-01-20 07:14:22 +02001265 The server is closed asynchronously, use the :meth:`wait_closed`
1266 coroutine to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +01001267
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +05301268 .. method:: get_loop()
1269
1270 Gives the event loop associated with the server object.
1271
1272 .. versionadded:: 3.7
1273
Yury Selivanovc9070d02018-01-25 18:08:09 -05001274 .. coroutinemethod:: start_serving()
1275
1276 Start accepting connections.
1277
1278 This method is idempotent, so it can be called when
1279 the server is already being serving.
1280
1281 The new *start_serving* keyword-only parameter to
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001282 :meth:`loop.create_server` and
Yury Selivanovc9070d02018-01-25 18:08:09 -05001283 :meth:`asyncio.start_server` allows to create a Server object
1284 that is not accepting connections right away. In which case
1285 this method, or :meth:`Server.serve_forever` can be used
1286 to make the Server object to start accepting connections.
1287
1288 .. versionadded:: 3.7
1289
1290 .. coroutinemethod:: serve_forever()
1291
1292 Start accepting connections until the coroutine is cancelled.
1293 Cancellation of ``serve_forever`` task causes the server
1294 to be closed.
1295
1296 This method can be called if the server is already accepting
1297 connections. Only one ``serve_forever`` task can exist per
1298 one *Server* object.
1299
1300 Example::
1301
1302 async def client_connected(reader, writer):
1303 # Communicate with the client with
1304 # reader/writer streams. For example:
1305 await reader.readline()
1306
1307 async def main(host, port):
1308 srv = await asyncio.start_server(
1309 client_connected, host, port)
Andrew Svetlov17ab8f02018-02-17 19:44:35 +02001310 await srv.serve_forever()
Yury Selivanovc9070d02018-01-25 18:08:09 -05001311
1312 asyncio.run(main('127.0.0.1', 0))
1313
1314 .. versionadded:: 3.7
1315
1316 .. method:: is_serving()
1317
1318 Return ``True`` if the server is accepting new connections.
1319
1320 .. versionadded:: 3.7
1321
Victor Stinnerbdd574d2015-02-12 22:49:18 +01001322 .. coroutinemethod:: wait_closed()
Victor Stinner8c462c52014-01-24 18:11:43 +01001323
Victor Stinner8ebeb032014-07-11 23:47:40 +02001324 Wait until the :meth:`close` method completes.
1325
Victor Stinner8ebeb032014-07-11 23:47:40 +02001326 .. attribute:: sockets
1327
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001328 List of :class:`socket.socket` objects the server is listening to,
1329 or ``None`` if the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +01001330
Yury Selivanovc9070d02018-01-25 18:08:09 -05001331 .. versionchanged:: 3.7
1332 Prior to Python 3.7 ``Server.sockets`` used to return the
1333 internal list of server's sockets directly. In 3.7 a copy
1334 of that list is returned.
1335
Victor Stinner8c462c52014-01-24 18:11:43 +01001336
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001337.. _asyncio-event-loops:
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001338
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001339Event Loops Implementations
1340===========================
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001341
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001342asyncio ships with two different event loop implementations:
1343:class:`SelectorEventLoop` and :class:`ProactorEventLoop`.
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001344
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001345By default asyncio is configured to use :class:`SelectorEventLoop`
1346on all platforms.
Andrew Svetlov3d4dbd82018-02-01 19:59:32 +02001347
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001348
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001349.. class:: SelectorEventLoop
1350
1351 An event loop based on the :mod:`selectors` module.
1352
1353 Uses the most efficient *selector* available for the given
1354 platform. It is also possible to manually configure what
1355 exact selector implementation should be used::
1356
1357 import asyncio
1358 import selectors
1359
1360 selector = selectors.SelectSelector()
1361 loop = asyncio.SelectorEventLoop(selector)
1362 asyncio.set_event_loop(loop)
Andrew Svetlov7464e872018-01-19 20:04:29 +02001363
1364
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001365 Availability: UNIX, Windows.
Andrew Svetlov7464e872018-01-19 20:04:29 +02001366
1367
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001368.. class:: ProactorEventLoop
1369
1370 An event loop for Windows that uses "I/O Completion Ports" (IOCP).
1371
1372 Availability: Windows.
1373
1374 An example how to use :class:`ProactorEventLoop` on Windows::
1375
1376 import asyncio
1377 import sys
1378
1379 if sys.platform == 'win32':
1380 loop = asyncio.ProactorEventLoop()
1381 asyncio.set_event_loop(loop)
1382
1383 .. seealso::
1384
1385 `MSDN documentation on I/O Completion Ports
1386 <https://docs.microsoft.com/en-ca/windows/desktop/FileIO/i-o-completion-ports>`_.
1387
1388
1389.. class:: AbstractEventLoop
1390
1391 Abstract base class for asyncio-compliant event loops.
1392
1393 The :ref:`Event Loop Methods <asyncio-event-loop>` section lists all
1394 methods that an alternative implementation of ``AbstractEventLoop``
1395 should have defined.
1396
1397
1398Examples
1399========
1400
1401Note that all examples in this section **purposefully** show how
1402to use low-level event loop APIs such as :meth:`loop.run_forever`
1403and :meth:`loop.call_soon`. Modern asyncio applications rarely
1404need to be written this way; consider using high-level functions
1405like :func:`asyncio.run`.
1406
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001407
Victor Stinner3e09e322013-12-03 01:22:06 +01001408.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +01001409
Victor Stinner7f314ed2014-10-15 18:49:16 +02001410Hello World with call_soon()
Victor Stinnera092a612015-01-09 15:58:41 +01001411^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +01001412
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001413An example using the :meth:`loop.call_soon` method to schedule a
1414callback. The callback displays ``"Hello World"`` and then stops the
1415event loop::
Victor Stinnerea3183f2013-12-03 01:08:00 +01001416
1417 import asyncio
1418
Victor Stinner7f314ed2014-10-15 18:49:16 +02001419 def hello_world(loop):
Carol Willing5b7cbd62018-09-12 17:05:17 -07001420 """A callback to print 'Hello World' and stop the event loop"""
Victor Stinnerea3183f2013-12-03 01:08:00 +01001421 print('Hello World')
Victor Stinner7f314ed2014-10-15 18:49:16 +02001422 loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +01001423
1424 loop = asyncio.get_event_loop()
Victor Stinner7f314ed2014-10-15 18:49:16 +02001425
1426 # Schedule a call to hello_world()
1427 loop.call_soon(hello_world, loop)
1428
1429 # Blocking call interrupted by loop.stop()
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001430 try:
1431 loop.run_forever()
1432 finally:
1433 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +01001434
Victor Stinner3e09e322013-12-03 01:22:06 +01001435.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +01001436
Yury Selivanov3faaa882018-09-14 13:32:07 -07001437 A similar :ref:`Hello World <coroutine>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001438 example created with a coroutine and the :func:`run` function.
Victor Stinnerea3183f2013-12-03 01:08:00 +01001439
Victor Stinner8b863482014-01-27 10:07:50 +01001440
Victor Stinner7f314ed2014-10-15 18:49:16 +02001441.. _asyncio-date-callback:
1442
1443Display the current date with call_later()
Victor Stinnera092a612015-01-09 15:58:41 +01001444^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner7f314ed2014-10-15 18:49:16 +02001445
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001446An example of callback displaying the current date every second. The
1447callback uses the :meth:`loop.call_later` method to reschedule itself
1448during 5 seconds, and then stops the event loop::
Victor Stinner7f314ed2014-10-15 18:49:16 +02001449
1450 import asyncio
1451 import datetime
1452
1453 def display_date(end_time, loop):
1454 print(datetime.datetime.now())
1455 if (loop.time() + 1.0) < end_time:
1456 loop.call_later(1, display_date, end_time, loop)
1457 else:
1458 loop.stop()
1459
1460 loop = asyncio.get_event_loop()
1461
1462 # Schedule the first call to display_date()
1463 end_time = loop.time() + 5.0
1464 loop.call_soon(display_date, end_time, loop)
1465
1466 # Blocking call interrupted by loop.stop()
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001467 try:
1468 loop.run_forever()
1469 finally:
1470 loop.close()
Victor Stinner7f314ed2014-10-15 18:49:16 +02001471
1472.. seealso::
1473
Yury Selivanov7372c3b2018-09-14 15:11:24 -07001474 A similar :ref:`current date <asyncio_example_sleep>` example
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001475 created with a coroutine and the :func:`run` function.
Victor Stinner7f314ed2014-10-15 18:49:16 +02001476
1477
Victor Stinner04e6df32014-10-11 16:16:27 +02001478.. _asyncio-watch-read-event:
Victor Stinner8b863482014-01-27 10:07:50 +01001479
Victor Stinner04e6df32014-10-11 16:16:27 +02001480Watch a file descriptor for read events
Victor Stinnera092a612015-01-09 15:58:41 +01001481^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +02001482
1483Wait until a file descriptor received some data using the
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001484:meth:`loop.add_reader` method and then close the event loop::
Victor Stinner04e6df32014-10-11 16:16:27 +02001485
1486 import asyncio
Victor Stinnerac577d72017-11-28 21:33:20 +01001487 from socket import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +02001488
1489 # Create a pair of connected file descriptors
Victor Stinnerccd8e342014-10-11 16:30:02 +02001490 rsock, wsock = socketpair()
Carol Willing5b7cbd62018-09-12 17:05:17 -07001491
Victor Stinner04e6df32014-10-11 16:16:27 +02001492 loop = asyncio.get_event_loop()
1493
1494 def reader():
1495 data = rsock.recv(100)
1496 print("Received:", data.decode())
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001497
Victor Stinner2cef3002014-10-23 22:38:46 +02001498 # We are done: unregister the file descriptor
Victor Stinner04e6df32014-10-11 16:16:27 +02001499 loop.remove_reader(rsock)
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001500
Victor Stinner04e6df32014-10-11 16:16:27 +02001501 # Stop the event loop
1502 loop.stop()
1503
Victor Stinner2cef3002014-10-23 22:38:46 +02001504 # Register the file descriptor for read event
Victor Stinner04e6df32014-10-11 16:16:27 +02001505 loop.add_reader(rsock, reader)
1506
1507 # Simulate the reception of data from the network
1508 loop.call_soon(wsock.send, 'abc'.encode())
1509
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001510 try:
1511 # Run the event loop
1512 loop.run_forever()
1513 finally:
Carol Willing5b7cbd62018-09-12 17:05:17 -07001514 # We are done. Close sockets and the event loop.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001515 rsock.close()
1516 wsock.close()
1517 loop.close()
Victor Stinner04e6df32014-10-11 16:16:27 +02001518
1519.. seealso::
1520
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001521 * A similar :ref:`example <asyncio-register-socket>`
1522 using transports, protocols, and the
1523 :meth:`loop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +02001524
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001525 * Another similar :ref:`example <asyncio-register-socket-streams>`
1526 using the high-level :func:`asyncio.open_connection` function
1527 and streams.
Victor Stinner04e6df32014-10-11 16:16:27 +02001528
1529
1530Set signal handlers for SIGINT and SIGTERM
Victor Stinnera092a612015-01-09 15:58:41 +01001531^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +02001532
Carol Willing5b7cbd62018-09-12 17:05:17 -07001533(This ``signals`` example only works on UNIX.)
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001534
1535Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`
1536using the :meth:`loop.add_signal_handler` method::
Victor Stinner8b863482014-01-27 10:07:50 +01001537
1538 import asyncio
1539 import functools
1540 import os
1541 import signal
1542
1543 def ask_exit(signame):
1544 print("got signal %s: exit" % signame)
1545 loop.stop()
1546
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001547 async def main():
1548 loop = asyncio.get_running_loop()
Victor Stinner8b863482014-01-27 10:07:50 +01001549
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001550 for signame in {'SIGINT', 'SIGTERM'}:
1551 loop.add_signal_handler(
1552 getattr(signal, signame),
1553 functools.partial(ask_exit, signame))
Victor Stinner2cef3002014-10-23 22:38:46 +02001554
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001555 await asyncio.sleep(3600)
1556
1557 print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
1558 print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")
1559
1560 asyncio.run(main())