blob: c200844385c117351c3dd5df407f2f80637ca524 [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
11An event loop is the central component of every asyncio application.
12Event loops run asynchronous tasks and callbacks, perform network
13IO operations, run subprocesses, etc.
14
15In general, it is *not recommended* to use event loops directly at
16the application-level asyncio code. They should only be accessed
17in low-level code in libraries and frameworks.
18
19High-level asyncio applications should not need to work with event
20loops and should use the :func:`asyncio.run` function to initialize
21and run asynchronous code.
22
23
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
45 Because this function has a rather complex behavior (especially
46 when custom event loop policies are in use), it is recommended
47 to use the :func:`get_running_loop` function in coroutines and
48 callbacks instead.
49
50 Consider also using the :func:`asyncio.run` function instead of
51 manually creating and closing an event loop.
52
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
70* The `Event Loop Methods`_ section is a reference documentation of
71 event loop APIs;
72
73* The `Callback Handles`_ section documents the :class:`Handle` and
74 :class:`TimerHandle`, instances of which are returned from functions
75 :meth:`loop.call_soon`, :meth:`loop.call_later`, etc;
76
77* The `Server Objects`_ sections documents types returned from
78 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
Yury Selivanov7c7605f2018-09-11 09:54:40 -070092Event loops provide the following **low-level** APIs:
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.
123 Note that callbacks scheduled by callbacks will not run in that
124 case; they will run the next time :meth:`run_forever` or
125 :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
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700143 The loop cannot not be running when this function is called.
144 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
157 is iterated. Should be used to reliably finalize all scheduled
158 asynchronous generators, e.g.:
Yury Selivanov03660042016-12-15 17:36:05 -0500159
160 try:
161 loop.run_forever()
162 finally:
163 loop.run_until_complete(loop.shutdown_asyncgens())
164 loop.close()
165
166 .. versionadded:: 3.6
167
168
Victor Stinner8464c242014-11-28 13:15:41 +0100169.. _asyncio-pass-keywords:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100170
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700171Scheduling callbacks
172^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100173
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700174.. method:: loop.call_soon(callback, *args, context=None)
Victor Stinner8464c242014-11-28 13:15:41 +0100175
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700176 Schedule *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 Selivanov7c7605f2018-09-11 09:54:40 -0700179 Callbacks are called in the order in which they are registered.
180 Each callback will be called exactly once.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100181
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700182 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.
Yury Selivanov28b91782018-05-23 13:35:04 -0400185
Yury Selivanov1096f762015-06-25 13:49:52 -0400186 An instance of :class:`asyncio.Handle` is returned, which can be
187 used to cancel the callback.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500188
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700189.. method:: loop.call_soon_threadsafe(callback, *args, context=None)
Victor Stinner8464c242014-11-28 13:15:41 +0100190
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700191 A thread-safe variant of :meth:`call_soon`. Must be used to
192 schedule callbacks *from another thread*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100193
Victor Stinner83704962015-02-25 14:24:15 +0100194 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
195 section of the documentation.
196
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700197.. versionchanged:: 3.7
198 The *context* keyword-only parameter was added. See :pep:`567`
199 for more details.
200
201.. note::
202
203 Most :mod:`asyncio` scheduling functions don't allow to pass
204 keyword arguments. To do that, use :func:`functools.partial`,
205 e.g.::
206
207 # will schedule "print("Hello", flush=True)":
208 loop.call_soon(
209 functools.partial(print, "Hello", flush=True))
210
211 Using partial objects is usually more convenient than using lambdas,
212 as asyncio can better render partial objects in debug and error
213 messages.
Yury Selivanov28b91782018-05-23 13:35:04 -0400214
Victor Stinnerea3183f2013-12-03 01:08:00 +0100215
Victor Stinner45b27ed2014-02-01 02:36:43 +0100216.. _asyncio-delayed-calls:
217
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700218Scheduling delayed callbacks
219^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100220
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700221Event loop provides mechanisms to schedule callback functions
222to be called at some point in the future. Event loop uses monotonic
223clocks to track time.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100224
Victor Stinner45b27ed2014-02-01 02:36:43 +0100225
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700226.. method:: loop.call_later(delay, callback, *args, context=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100227
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700228 Schedule *callback* to be called after the given *delay*
229 number of seconds (can be either an int or a float).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100230
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700231 An instance of :class:`asyncio.TimerHandle` is returned which can
232 be used to cancel the callback.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100233
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700234 *callback* will be called exactly once. If two callbacks are
235 scheduled for exactly the same time, it is undefined which will
236 be called first.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100237
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700238 The optional positional *args* will be passed to the callback when
239 it is called. If you want the callback to be called with keyword
240 arguments use :func:`functools.partial`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100241
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700242 An optional keyword-only *context* argument allows specifying a
243 custom :class:`contextvars.Context` for the *callback* to run in.
244 The current context is used when no *context* is provided.
Victor Stinner8464c242014-11-28 13:15:41 +0100245
Yury Selivanov28b91782018-05-23 13:35:04 -0400246 .. versionchanged:: 3.7
247 The *context* keyword-only parameter was added. See :pep:`567`
248 for more details.
249
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700250.. method:: loop.call_at(when, callback, *args, context=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100251
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700252 Schedule *callback* to be called at the given absolute timestamp
253 *when* (an int or a float), using the same time reference as
254 :meth:`loop.time`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100255
256 This method's behavior is the same as :meth:`call_later`.
257
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700258 An instance of :class:`asyncio.TimerHandle` is returned which can
259 be used to cancel the callback.
Victor Stinner8464c242014-11-28 13:15:41 +0100260
Yury Selivanov28b91782018-05-23 13:35:04 -0400261 .. versionchanged:: 3.7
262 The *context* keyword-only parameter was added. See :pep:`567`
263 for more details.
264
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700265.. method:: loop.time()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100266
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700267 Return the current time, as a :class:`float` value, according to
268 the event loop's internal monotonic clock.
269
270.. note::
271
272 Timeouts (relative *delay* or absolute *when*) should not
273 exceed one day.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100274
Victor Stinner3e09e322013-12-03 01:22:06 +0100275.. seealso::
276
277 The :func:`asyncio.sleep` function.
278
Victor Stinnerea3183f2013-12-03 01:08:00 +0100279
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700280Creating Futures and Tasks
281^^^^^^^^^^^^^^^^^^^^^^^^^^
Yury Selivanov950204d2016-05-16 16:23:00 -0400282
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700283.. method:: loop.create_future()
Yury Selivanov950204d2016-05-16 16:23:00 -0400284
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700285 Create an :class:`asyncio.Future` object attached to the event loop.
Yury Selivanov950204d2016-05-16 16:23:00 -0400286
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700287 This is the preferred way to create Futures in asyncio, that lets
288 third-party event loops to provide alternative implementations of
289 the Future object (with better performance or instrumentation).
Yury Selivanov950204d2016-05-16 16:23:00 -0400290
291 .. versionadded:: 3.5.2
292
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700293.. method:: loop.create_task(coro, \*, name=None)
Yury Selivanov950204d2016-05-16 16:23:00 -0400294
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700295 Schedule the execution of a :ref:`coroutine`.
296 Return a :class:`Task` object.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200297
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700298 Third-party event loops can use their own subclass of :class:`Task`
299 for interoperability. In this case, the result type is a subclass
300 of :class:`Task`.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200301
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700302 If the *name* argument is provided and not ``None``, it is set as
303 the name of the task using :meth:`Task.set_name`.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200304
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300305 .. versionchanged:: 3.8
306 Added the ``name`` parameter.
307
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700308.. method:: loop.set_task_factory(factory)
Yury Selivanov71854612015-05-11 16:28:27 -0400309
310 Set a task factory that will be used by
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700311 :meth:`loop.create_task`.
Yury Selivanov71854612015-05-11 16:28:27 -0400312
313 If *factory* is ``None`` the default task factory will be set.
314
315 If *factory* is a *callable*, it should have a signature matching
316 ``(loop, coro)``, where *loop* will be a reference to the active
317 event loop, *coro* will be a coroutine object. The callable
318 must return an :class:`asyncio.Future` compatible object.
319
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700320.. method:: loop.get_task_factory()
Yury Selivanov71854612015-05-11 16:28:27 -0400321
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700322 Return a task factory or ``None`` if the default one is in use.
Yury Selivanov71854612015-05-11 16:28:27 -0400323
Victor Stinner530ef2f2014-07-08 12:39:10 +0200324
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700325Opening network connections
326^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100327
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700328.. coroutinemethod:: loop.create_connection(protocol_factory, \
329 host=None, port=None, \*, ssl=None, \
330 family=0, proto=0, flags=0, sock=None, \
331 local_addr=None, server_hostname=None, \
332 ssl_handshake_timeout=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100333
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700334 Open a streaming transport connection to a given
335 address specified by *host* and *port*.
336
337 The socket family can be either :py:data:`~socket.AF_INET` or
338 :py:data:`~socket.AF_INET6` depending on *host* (or the *family*
339 argument, if provided).
340
341 The socket type will be :py:data:`~socket.SOCK_STREAM`.
342
343 *protocol_factory* must be a callable returning an
344 :ref:`asyncio protocol <asyncio-protocol>` implementation.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100345
Yury Selivanov19a44f62017-12-14 20:53:26 -0500346 This method will try to establish the connection in the background.
347 When successful, it returns a ``(transport, protocol)`` pair.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100348
349 The chronological synopsis of the underlying operation is as follows:
350
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700351 #. The connection is established and a :ref:`transport <asyncio-transport>`
352 is created for it.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100353
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700354 #. *protocol_factory* is called without arguments and is expected to
355 return a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100356
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700357 #. The protocol instance is coupled with the transport by calling its
358 :meth:`~BaseProtocol.connection_made` method.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100359
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700360 #. A ``(transport, protocol)`` tuple is returned on success.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100361
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700362 The created transport is an implementation-dependent bidirectional
363 stream.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100364
365 .. note::
366 *protocol_factory* can be any kind of callable, not necessarily
367 a class. For example, if you want to use a pre-created
368 protocol instance, you can pass ``lambda: my_protocol``.
369
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700370 Other arguments:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100371
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700372 * *ssl*: if given and not false, an SSL/TLS transport is created
Victor Stinnerea3183f2013-12-03 01:08:00 +0100373 (by default a plain TCP transport is created). If *ssl* is
374 a :class:`ssl.SSLContext` object, this context is used to create
375 the transport; if *ssl* is :const:`True`, a context with some
376 unspecified default settings is used.
377
Berker Peksag9c1dba22014-09-28 00:00:58 +0300378 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100379
Victor Stinnerea3183f2013-12-03 01:08:00 +0100380 * *server_hostname*, is only for use together with *ssl*,
381 and sets or overrides the hostname that the target server's certificate
382 will be matched against. By default the value of the *host* argument
383 is used. If *host* is empty, there is no default and you must pass a
384 value for *server_hostname*. If *server_hostname* is an empty
385 string, hostname matching is disabled (which is a serious security
386 risk, allowing for man-in-the-middle-attacks).
387
388 * *family*, *proto*, *flags* are the optional address family, protocol
389 and flags to be passed through to getaddrinfo() for *host* resolution.
390 If given, these should all be integers from the corresponding
391 :mod:`socket` module constants.
392
393 * *sock*, if given, should be an existing, already connected
394 :class:`socket.socket` object to be used by the transport.
395 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
396 and *local_addr* should be specified.
397
398 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
399 to bind the socket to locally. The *local_host* and *local_port*
400 are looked up using getaddrinfo(), similarly to *host* and *port*.
401
Neil Aspinallf7686c12017-12-19 19:45:42 +0000402 * *ssl_handshake_timeout* is (for an SSL connection) the time in seconds
403 to wait for the SSL handshake to complete before aborting the connection.
Yury Selivanov96026432018-06-04 11:32:35 -0400404 ``60.0`` seconds if ``None`` (default).
Neil Aspinallf7686c12017-12-19 19:45:42 +0000405
406 .. versionadded:: 3.7
407
408 The *ssl_handshake_timeout* parameter.
409
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700410 .. versionchanged:: 3.6
411
412 The socket option :py:data:`~socket.TCP_NODELAY` is set by default
413 for all TCP connections.
414
Victor Stinner60208a12015-09-15 22:41:52 +0200415 .. versionchanged:: 3.5
416
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700417 Added support for SSL/TLS for :class:`ProactorEventLoop`.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200418
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100419 .. seealso::
420
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700421 The :func:`open_connection` function is a high-level alternative
422 API. It returns a pair of (:class:`StreamReader`, :class:`StreamWriter`)
423 that can be used directly in async/await code.
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100424
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700425.. coroutinemethod:: loop.create_datagram_endpoint(protocol_factory, \
426 local_addr=None, remote_addr=None, \*, \
427 family=0, proto=0, flags=0, \
428 reuse_address=None, reuse_port=None, \
429 allow_broadcast=None, sock=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100430
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700431 Create a datagram connection.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100432
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700433 The socket family can be either :py:data:`~socket.AF_INET`,
434 :py:data:`~socket.AF_INET6`, or :py:data:`~socket.AF_UNIX`,
435 depending on *host* (or the *family* argument, if provided).
Victor Stinnera6919aa2014-02-19 13:32:34 +0100436
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700437 The socket type will be :py:data:`~socket.SOCK_DGRAM`.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100438
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700439 *protocol_factory* must be a callable returning a
440 :ref:`protocol <asyncio-protocol>` implementation.
441
442 A tuple of ``(transport, protocol)`` is returned on success.
443
444 Other arguments:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700445
446 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
447 to bind the socket to locally. The *local_host* and *local_port*
448 are looked up using :meth:`getaddrinfo`.
449
450 * *remote_addr*, if given, is a ``(remote_host, remote_port)`` tuple used
451 to connect the socket to a remote address. The *remote_host* and
452 *remote_port* are looked up using :meth:`getaddrinfo`.
453
454 * *family*, *proto*, *flags* are the optional address family, protocol
455 and flags to be passed through to :meth:`getaddrinfo` for *host*
456 resolution. If given, these should all be integers from the
457 corresponding :mod:`socket` module constants.
458
459 * *reuse_address* tells the kernel to reuse a local socket in
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700460 ``TIME_WAIT`` state, without waiting for its natural timeout to
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300461 expire. If not specified will automatically be set to ``True`` on
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700462 UNIX.
463
464 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
465 same port as other existing endpoints are bound to, so long as they all
466 set this flag when being created. This option is not supported on Windows
467 and some UNIX's. If the :py:data:`~socket.SO_REUSEPORT` constant is not
468 defined then this capability is unsupported.
469
470 * *allow_broadcast* tells the kernel to allow this endpoint to send
471 messages to the broadcast address.
472
473 * *sock* can optionally be specified in order to use a preexisting,
474 already connected, :class:`socket.socket` object to be used by the
475 transport. If specified, *local_addr* and *remote_addr* should be omitted
476 (must be :const:`None`).
Victor Stinnera6919aa2014-02-19 13:32:34 +0100477
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200478 On Windows with :class:`ProactorEventLoop`, this method is not supported.
479
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200480 See :ref:`UDP echo client protocol <asyncio-udp-echo-client-protocol>` and
481 :ref:`UDP echo server protocol <asyncio-udp-echo-server-protocol>` examples.
482
Romuald Brunet0ded5802018-05-14 18:22:00 +0200483 .. versionchanged:: 3.4.4
484 The *family*, *proto*, *flags*, *reuse_address*, *reuse_port,
485 *allow_broadcast*, and *sock* parameters were added.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100486
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700487.. coroutinemethod:: loop.create_unix_connection(protocol_factory, \
488 path=None, \*, ssl=None, sock=None, \
489 server_hostname=None, ssl_handshake_timeout=None)
Victor Stinnera6919aa2014-02-19 13:32:34 +0100490
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700491 Create UNIX connection.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100492
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700493 The socket family will be :py:data:`~socket.AF_UNIX`; socket
494 type will be :py:data:`~socket.SOCK_STREAM`.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100495
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700496 A tuple of ``(transport, protocol)`` is returned on success.
Guido van Rossum9e80eeb2016-11-03 14:17:25 -0700497
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700498 *path* is the name of a UNIX domain socket and is required,
499 unless a *sock* parameter is specified. Abstract UNIX sockets,
500 :class:`str`, :class:`bytes`, and :class:`~pathlib.Path` paths are
501 supported.
502
503 See the documentation of the :meth:`loop.create_connection` method
504 for information about arguments to this method.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100505
506 Availability: UNIX.
507
Neil Aspinallf7686c12017-12-19 19:45:42 +0000508 .. versionadded:: 3.7
509
510 The *ssl_handshake_timeout* parameter.
511
Yury Selivanov423fd362017-11-20 17:26:28 -0500512 .. versionchanged:: 3.7
513
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400514 The *path* parameter can now be a :term:`path-like object`.
Yury Selivanov423fd362017-11-20 17:26:28 -0500515
Victor Stinnera6919aa2014-02-19 13:32:34 +0100516
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700517Creating network servers
518^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100519
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700520.. coroutinemethod:: loop.create_server(protocol_factory, \
521 host=None, port=None, \*, \
522 family=socket.AF_UNSPEC, \
523 flags=socket.AI_PASSIVE, \
524 sock=None, backlog=100, ssl=None, \
525 reuse_address=None, reuse_port=None, \
526 ssl_handshake_timeout=None, start_serving=True)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100527
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700528 Create a TCP server (socket type :data:`~socket.SOCK_STREAM`) listening
529 on the *host* and *port* address.
Victor Stinner33f6abe2014-10-12 20:36:04 +0200530
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700531 Returns a :class:`Server` object.
Victor Stinner33f6abe2014-10-12 20:36:04 +0200532
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700533 Arguments:
Victor Stinner33f6abe2014-10-12 20:36:04 +0200534
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200535 * The *host* parameter can be a string, in that case the TCP server is
536 bound to *host* and *port*. The *host* parameter can also be a sequence
537 of strings and in that case the TCP server is bound to all hosts of the
538 sequence. If *host* is an empty string or ``None``, all interfaces are
539 assumed and a list of multiple sockets will be returned (most likely one
540 for IPv4 and another one for IPv6).
Victor Stinner33f6abe2014-10-12 20:36:04 +0200541
542 * *family* can be set to either :data:`socket.AF_INET` or
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700543 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6.
544 If not set it will be determined from host name
545 (defaults to :data:`~socket.AF_UNSPEC`).
Victor Stinner33f6abe2014-10-12 20:36:04 +0200546
547 * *flags* is a bitmask for :meth:`getaddrinfo`.
548
549 * *sock* can optionally be specified in order to use a preexisting
550 socket object. If specified, *host* and *port* should be omitted (must be
551 :const:`None`).
552
553 * *backlog* is the maximum number of queued connections passed to
554 :meth:`~socket.socket.listen` (defaults to 100).
555
556 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the
557 accepted connections.
558
559 * *reuse_address* tells the kernel to reuse a local socket in
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700560 ``TIME_WAIT`` state, without waiting for its natural timeout to
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300561 expire. If not specified will automatically be set to ``True`` on
Victor Stinner33f6abe2014-10-12 20:36:04 +0200562 UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100563
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700564 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
565 same port as other existing endpoints are bound to, so long as they all
566 set this flag when being created. This option is not supported on
567 Windows.
568
Neil Aspinallf7686c12017-12-19 19:45:42 +0000569 * *ssl_handshake_timeout* is (for an SSL server) the time in seconds to wait
570 for the SSL handshake to complete before aborting the connection.
Yury Selivanov96026432018-06-04 11:32:35 -0400571 ``60.0`` seconds if ``None`` (default).
Neil Aspinallf7686c12017-12-19 19:45:42 +0000572
Yury Selivanovc9070d02018-01-25 18:08:09 -0500573 * *start_serving* set to ``True`` (the default) causes the created server
574 to start accepting connections immediately. When set to ``False``,
575 the user should await on :meth:`Server.start_serving` or
576 :meth:`Server.serve_forever` to make the server to start accepting
577 connections.
578
Neil Aspinallf7686c12017-12-19 19:45:42 +0000579 .. versionadded:: 3.7
580
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700581 Added *ssl_handshake_timeout* and *start_serving* parameters.
582
583 .. versionchanged:: 3.6
584
585 The socket option :py:data:`~socket.TCP_NODELAY` is set by default
586 for all TCP connections.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000587
Victor Stinner60208a12015-09-15 22:41:52 +0200588 .. versionchanged:: 3.5
589
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700590 Added support for SSL/TLS on Windows with
591 :class:`ProactorEventLoop`.
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100592
Victor Stinner7b58a2b2015-09-21 18:41:05 +0200593 .. versionchanged:: 3.5.1
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200594
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700595 The *host* parameter can be a sequence of strings.
596
597 .. seealso::
598
599 The :func:`start_server` function is a higher-level alternative API
600 that returns a pair of :class:`StreamReader` and :class:`StreamWriter`
601 that can be used in an async/await code.
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200602
Victor Stinnerea3183f2013-12-03 01:08:00 +0100603
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700604.. coroutinemethod:: loop.create_unix_server(protocol_factory, path=None, \
605 \*, sock=None, backlog=100, ssl=None, \
606 ssl_handshake_timeout=None, start_serving=True)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100607
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700608 Similar to :meth:`loop.create_server` but works with the
609 :py:data:`~socket.AF_UNIX` socket family.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100610
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700611 *path* is the name of a UNIX domain socket, and is required,
612 unless a *sock* argument is provided. Abstract UNIX sockets,
613 :class:`str`, :class:`bytes`, and :class:`~pathlib.Path` paths
614 are supported.
Yury Selivanov423fd362017-11-20 17:26:28 -0500615
Victor Stinnera6919aa2014-02-19 13:32:34 +0100616 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100617
Neil Aspinallf7686c12017-12-19 19:45:42 +0000618 .. versionadded:: 3.7
619
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400620 The *ssl_handshake_timeout* and *start_serving* parameters.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000621
Yury Selivanov423fd362017-11-20 17:26:28 -0500622 .. versionchanged:: 3.7
623
624 The *path* parameter can now be a :class:`~pathlib.Path` object.
625
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700626.. coroutinemethod:: loop.connect_accepted_socket(protocol_factory, \
627 sock, \*, ssl=None, ssl_handshake_timeout=None)
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500628
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700629 Wrap an already accepted connection into a transport/protocol pair.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500630
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700631 This method can be used by servers that accept connections outside
632 of asyncio but that use asyncio to handle them.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500633
634 Parameters:
635
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700636 * *sock* is a preexisting socket object returned from
637 :meth:`socket.accept <socket.socket.accept>`.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500638
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700639 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over
640 the accepted connections.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500641
Neil Aspinallf7686c12017-12-19 19:45:42 +0000642 * *ssl_handshake_timeout* is (for an SSL connection) the time in seconds to
643 wait for the SSL handshake to complete before aborting the connection.
Yury Selivanov96026432018-06-04 11:32:35 -0400644 ``60.0`` seconds if ``None`` (default).
Neil Aspinallf7686c12017-12-19 19:45:42 +0000645
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700646 Returns a ``(transport, protocol)`` pair.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100647
Neil Aspinallf7686c12017-12-19 19:45:42 +0000648 .. versionadded:: 3.7
649
650 The *ssl_handshake_timeout* parameter.
651
AraHaan431665b2017-11-21 11:06:26 -0500652 .. versionadded:: 3.5.3
653
654
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700655Transferring files
656^^^^^^^^^^^^^^^^^^
Andrew Svetlov7c684072018-01-27 21:22:47 +0200657
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700658.. coroutinemethod:: loop.sendfile(transport, file, \
659 offset=0, count=None, *, fallback=True)
Andrew Svetlov7c684072018-01-27 21:22:47 +0200660
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700661 Send a *file* over a *transport*. Return the total number of bytes
662 sent.
Andrew Svetlov7c684072018-01-27 21:22:47 +0200663
664 The method uses high-performance :meth:`os.sendfile` if available.
665
666 *file* must be a regular file object opened in binary mode.
667
668 *offset* tells from where to start reading the file. If specified,
669 *count* is the total number of bytes to transmit as opposed to
670 sending the file until EOF is reached. File position is updated on
671 return or also in case of error in which case :meth:`file.tell()
672 <io.IOBase.tell>` can be used to figure out the number of bytes
673 which were sent.
674
675 *fallback* set to ``True`` makes asyncio to manually read and send
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700676 the file when the platform does not support the sendfile system call
Andrew Svetlov7c684072018-01-27 21:22:47 +0200677 (e.g. Windows or SSL socket on Unix).
678
679 Raise :exc:`SendfileNotAvailableError` if the system does not support
680 *sendfile* syscall and *fallback* is ``False``.
681
682 .. versionadded:: 3.7
683
684
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500685TLS Upgrade
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700686^^^^^^^^^^^
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500687
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700688.. coroutinemethod:: loop.start_tls(transport, protocol, \
689 sslcontext, \*, server_side=False, \
690 server_hostname=None, ssl_handshake_timeout=None)
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500691
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700692 Upgrade an existing transport-based connection to TLS.
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500693
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700694 Return a new transport instance, that the *protocol* must start using
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500695 immediately after the *await*. The *transport* instance passed to
696 the *start_tls* method should never be used again.
697
698 Parameters:
699
700 * *transport* and *protocol* instances that methods like
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700701 :meth:`~loop.create_server` and
702 :meth:`~loop.create_connection` return.
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500703
704 * *sslcontext*: a configured instance of :class:`~ssl.SSLContext`.
705
706 * *server_side* pass ``True`` when a server-side connection is being
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700707 upgraded (like the one created by :meth:`~loop.create_server`).
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500708
709 * *server_hostname*: sets or overrides the host name that the target
710 server's certificate will be matched against.
711
712 * *ssl_handshake_timeout* is (for an SSL connection) the time in seconds to
713 wait for the SSL handshake to complete before aborting the connection.
Yury Selivanov96026432018-06-04 11:32:35 -0400714 ``60.0`` seconds if ``None`` (default).
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500715
716 .. versionadded:: 3.7
717
718
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700719Watching file descriptors
720^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerc1567df2014-02-08 23:22:58 +0100721
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700722.. method:: loop.add_reader(fd, callback, \*args)
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200723
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700724 Start watching the file descriptor for read availability and
725 call the *callback* with specified arguments.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200726
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700727.. method:: loop.remove_reader(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100728
729 Stop watching the file descriptor for read availability.
730
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700731.. method:: loop.add_writer(fd, callback, \*args)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100732
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700733 Start watching the file descriptor for write availability and then
734 call the *callback* with specified arguments.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100735
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700736 Use :func:`functools.partial` :ref:`to pass keywords
737 <asyncio-pass-keywords>` to *func*.
Victor Stinner8464c242014-11-28 13:15:41 +0100738
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700739.. method:: loop.remove_writer(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100740
741 Stop watching the file descriptor for write availability.
742
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700743See also :ref:`Platform Support <asyncio-platform-support>` section
744for some limitations of these methods.
Victor Stinner04e6df32014-10-11 16:16:27 +0200745
Victor Stinnerc1567df2014-02-08 23:22:58 +0100746
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700747Working with socket objects directly
748^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerc1567df2014-02-08 23:22:58 +0100749
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700750In general, protocols implementations that use transport-based APIs
751such as :meth:`loop.create_connection` and :meth:`loop.create_server`
752are faster than implementations that work with sockets directly.
753However, there are use cases when performance is not critical and
754working with :class:`~socket.socket` objects directly is more
755convenient.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100756
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700757.. coroutinemethod:: loop.sock_recv(sock, nbytes)
Yury Selivanov55c50842016-06-08 12:48:15 -0400758
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700759 Receive data. Asynchronous version of
760 :meth:`socket.recv() <socket.socket.recv>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100761
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700762 The received data is returned as a bytes object. The maximum amount
763 of data to be received is specified by the *nbytes* argument.
764
765 The socket *sock* must be non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200766
Yury Selivanov19a44f62017-12-14 20:53:26 -0500767 .. versionchanged:: 3.7
768 Even though the method was always documented as a coroutine
769 method, before Python 3.7 it returned a :class:`Future`.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700770 Since Python 3.7 this is an ``async def`` method.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100771
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700772.. coroutinemethod:: loop.sock_recv_into(sock, buf)
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200773
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700774 Receive data into a buffer. Modeled after the blocking
775 :meth:`socket.recv_into() <socket.socket.recv_into>` method.
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200776
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700777 Return the number of bytes written to the buffer.
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200778
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700779 The socket *sock* must be non-blocking.
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200780
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200781 .. versionadded:: 3.7
782
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700783.. coroutinemethod:: loop.sock_sendall(sock, data)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100784
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700785 Send data to the socket. Asynchronous version of
786 :meth:`socket.sendall() <socket.socket.sendall>`.
Yury Selivanov55c50842016-06-08 12:48:15 -0400787
Victor Stinnerc1567df2014-02-08 23:22:58 +0100788 This method continues to send data from *data* until either all data has
789 been sent or an error occurs. ``None`` is returned on success. On error,
790 an exception is raised, and there is no way to determine how much data, if
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500791 any, was successfully processed by the receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100792
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700793 The socket *sock* must be non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200794
Yury Selivanov19a44f62017-12-14 20:53:26 -0500795 .. versionchanged:: 3.7
796 Even though the method was always documented as a coroutine
797 method, before Python 3.7 it returned an :class:`Future`.
798 Since Python 3.7, this is an ``async def`` method.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100799
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700800.. coroutinemethod:: loop.sock_connect(sock, address)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100801
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700802 Connect to a remote socket at *address*.
Victor Stinner1b0580b2014-02-13 09:24:37 +0100803
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700804 Asynchronous version of :meth:`socket.connect() <socket.socket.connect>`.
805
806 The socket *sock* must be non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200807
Yury Selivanov55c50842016-06-08 12:48:15 -0400808 .. versionchanged:: 3.5.2
809 ``address`` no longer needs to be resolved. ``sock_connect``
810 will try to check if the *address* is already resolved by calling
811 :func:`socket.inet_pton`. If not,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700812 :meth:`loop.getaddrinfo` will be used to resolve the
Yury Selivanov55c50842016-06-08 12:48:15 -0400813 *address*.
814
Victor Stinnerc1567df2014-02-08 23:22:58 +0100815 .. seealso::
816
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700817 :meth:`loop.create_connection`
Yury Selivanov55c50842016-06-08 12:48:15 -0400818 and :func:`asyncio.open_connection() <open_connection>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100819
820
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700821.. coroutinemethod:: loop.sock_accept(sock)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100822
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700823 Accept a connection. Modeled after the blocking
824 :meth:`socket.accept() <socket.socket.accept>` method.
Yury Selivanov55c50842016-06-08 12:48:15 -0400825
826 The socket must be bound to an address and listening
Victor Stinnerc1567df2014-02-08 23:22:58 +0100827 for connections. The return value is a pair ``(conn, address)`` where *conn*
828 is a *new* socket object usable to send and receive data on the connection,
829 and *address* is the address bound to the socket on the other end of the
830 connection.
831
Victor Stinnerec2ce092014-07-29 23:12:22 +0200832 The socket *sock* must be non-blocking.
833
Yury Selivanov19a44f62017-12-14 20:53:26 -0500834 .. versionchanged:: 3.7
835 Even though the method was always documented as a coroutine
836 method, before Python 3.7 it returned a :class:`Future`.
837 Since Python 3.7, this is an ``async def`` method.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100838
839 .. seealso::
840
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700841 :meth:`loop.create_server` and :func:`start_server`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100842
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700843.. coroutinemethod:: loop.sock_sendfile(sock, file, offset=0, count=None, \
844 \*, fallback=True)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200845
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700846 Send a file using high-performance :mod:`os.sendfile` if possible.
847 Return the total number of bytes which were sent.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200848
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700849 Asynchronous version of :meth:`socket.sendfile() <socket.socket.sendfile>`.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200850
851 *sock* must be non-blocking :class:`~socket.socket` of
852 :const:`socket.SOCK_STREAM` type.
853
854 *file* must be a regular file object opened in binary mode.
855
856 *offset* tells from where to start reading the file. If specified,
857 *count* is the total number of bytes to transmit as opposed to
858 sending the file until EOF is reached. File position is updated on
859 return or also in case of error in which case :meth:`file.tell()
860 <io.IOBase.tell>` can be used to figure out the number of bytes
861 which were sent.
862
863 *fallback* set to ``True`` makes asyncio to manually read and send
864 the file when the platform does not support the sendfile syscall
865 (e.g. Windows or SSL socket on Unix).
866
Andrew Svetlov7464e872018-01-19 20:04:29 +0200867 Raise :exc:`SendfileNotAvailableError` if the system does not support
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200868 *sendfile* syscall and *fallback* is ``False``.
869
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700870 The socket *sock* must be non-blocking.
871
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200872 .. versionadded:: 3.7
873
Victor Stinnerc1567df2014-02-08 23:22:58 +0100874
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700875DNS
876^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100877
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700878.. coroutinemethod:: loop.getaddrinfo(host, port, \*, family=0, \
879 type=0, proto=0, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100880
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700881 Asynchronous version of :meth:`socket.getaddrinfo`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100882
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700883.. coroutinemethod:: loop.getnameinfo(sockaddr, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100884
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700885 Asynchronous version of :meth:`socket.getnameinfo`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100886
Yury Selivanovbec23722018-01-28 14:09:40 -0500887.. versionchanged:: 3.7
888 Both *getaddrinfo* and *getnameinfo* methods were always documented
889 to return a coroutine, but prior to Python 3.7 they were, in fact,
890 returning :class:`asyncio.Future` objects. Starting with Python 3.7
891 both methods are coroutines.
892
Victor Stinnerea3183f2013-12-03 01:08:00 +0100893
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700894Working with pipes
895^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100896
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700897.. coroutinemethod:: loop.connect_read_pipe(protocol_factory, pipe)
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200898
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700899 Register a read-pipe in the event loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100900
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700901 *protocol_factory* must be a callable returning an
902 :ref:`asyncio protocol <asyncio-protocol>` implementation.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100903
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700904 *pipe* is a :term:`file-like object <file object>`.
905
906 Return pair ``(transport, protocol)``, where *transport* supports
907 the :class:`ReadTransport` interface.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100908
Victor Stinnerd84fd732014-08-26 01:01:59 +0200909 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
910 non-blocking mode.
911
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700912.. coroutinemethod:: loop.connect_write_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100913
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700914 Register a write-pipe in the event loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100915
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700916 *protocol_factory* must be a callable returning an
917 :ref:`asyncio protocol <asyncio-protocol>` implementation.
918
919 *pipe* is :term:`file-like object <file object>`.
920
Victor Stinner2cef3002014-10-23 22:38:46 +0200921 Return pair ``(transport, protocol)``, where *transport* supports
Victor Stinnerea3183f2013-12-03 01:08:00 +0100922 :class:`WriteTransport` interface.
923
Victor Stinnerd84fd732014-08-26 01:01:59 +0200924 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
925 non-blocking mode.
926
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700927.. note::
928
929 :class:`SelectorEventLoop` does not support the above methods on
930 Windows. Use :class:`ProactorEventLoop` instead.
931
Victor Stinner08444382014-02-02 22:43:39 +0100932.. seealso::
933
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700934 The :meth:`loop.subprocess_exec` and
935 :meth:`loop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100936
Victor Stinnerea3183f2013-12-03 01:08:00 +0100937
Victor Stinner8b863482014-01-27 10:07:50 +0100938UNIX signals
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700939^^^^^^^^^^^^
Victor Stinner8b863482014-01-27 10:07:50 +0100940
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700941.. method:: loop.add_signal_handler(signum, callback, \*args)
Victor Stinner8b863482014-01-27 10:07:50 +0100942
943 Add a handler for a signal.
944
945 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
946 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
947
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700948 Use :func:`functools.partial` :ref:`to pass keywords
949 <asyncio-pass-keywords>` to *func*.
Victor Stinner8464c242014-11-28 13:15:41 +0100950
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700951.. method:: loop.remove_signal_handler(sig)
Victor Stinner8b863482014-01-27 10:07:50 +0100952
953 Remove a handler for a signal.
954
955 Return ``True`` if a signal handler was removed, ``False`` if not.
956
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700957Availability: UNIX.
958
Victor Stinner8b863482014-01-27 10:07:50 +0100959.. seealso::
960
961 The :mod:`signal` module.
962
963
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700964Executing code in thread or process pools
965^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100966
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700967.. method:: loop.run_in_executor(executor, func, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100968
Andrew Svetlov1c62b522015-10-01 09:48:08 +0300969 Arrange for a *func* to be called in the specified executor.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100970
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700971 The *executor* argument should be an :class:`concurrent.futures.Executor`
Larry Hastings3732ed22014-03-15 21:13:56 -0700972 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100973
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700974 Use :func:`functools.partial` :ref:`to pass keywords
975 <asyncio-pass-keywords>` to *func*.
Victor Stinner8464c242014-11-28 13:15:41 +0100976
Yury Selivanovbec23722018-01-28 14:09:40 -0500977 This method returns a :class:`asyncio.Future` object.
978
Yury Selivanove8a60452016-10-21 17:40:42 -0400979 .. versionchanged:: 3.5.3
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700980 :meth:`loop.run_in_executor` no longer configures the
Yury Selivanove8a60452016-10-21 17:40:42 -0400981 ``max_workers`` of the thread pool executor it creates, instead
982 leaving it up to the thread pool executor
983 (:class:`~concurrent.futures.ThreadPoolExecutor`) to set the
984 default.
985
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700986.. method:: loop.set_default_executor(executor)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100987
Elvis Pranskevichus22d25082018-07-30 11:42:43 +0100988 Set *executor* as the default executor used by :meth:`run_in_executor`.
989 *executor* should be an instance of
990 :class:`~concurrent.futures.ThreadPoolExecutor`.
991
992 .. deprecated:: 3.8
993 Using an executor that is not an instance of
994 :class:`~concurrent.futures.ThreadPoolExecutor` is deprecated and
995 will trigger an error in Python 3.9.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100996
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700997 *executor* must be an instance of
998 :class:`concurrent.futures.ThreadPoolExecutor`.
999
Victor Stinnerea3183f2013-12-03 01:08:00 +01001000
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001001Error Handling API
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001002^^^^^^^^^^^^^^^^^^
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001003
Martin Panterc04fb562016-02-10 05:44:01 +00001004Allows customizing how exceptions are handled in the event loop.
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001005
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001006.. method:: loop.set_exception_handler(handler)
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001007
1008 Set *handler* as the new event loop exception handler.
1009
1010 If *handler* is ``None``, the default exception handler will
1011 be set.
1012
1013 If *handler* is a callable object, it should have a
1014 matching signature to ``(loop, context)``, where ``loop``
1015 will be a reference to the active event loop, ``context``
1016 will be a ``dict`` object (see :meth:`call_exception_handler`
1017 documentation for details about context).
1018
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001019.. method:: loop.get_exception_handler()
Yury Selivanov950204d2016-05-16 16:23:00 -04001020
1021 Return the exception handler, or ``None`` if the default one
1022 is in use.
1023
1024 .. versionadded:: 3.5.2
1025
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001026.. method:: loop.default_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001027
1028 Default exception handler.
1029
1030 This is called when an exception occurs and no exception
1031 handler is set, and can be called by a custom exception
1032 handler that wants to defer to the default behavior.
1033
1034 *context* parameter has the same meaning as in
1035 :meth:`call_exception_handler`.
1036
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001037.. method:: loop.call_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001038
1039 Call the current event loop exception handler.
1040
1041 *context* is a ``dict`` object containing the following keys
1042 (new keys may be introduced later):
1043
1044 * 'message': Error message;
1045 * 'exception' (optional): Exception object;
1046 * 'future' (optional): :class:`asyncio.Future` instance;
1047 * 'handle' (optional): :class:`asyncio.Handle` instance;
1048 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
1049 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
1050 * 'socket' (optional): :class:`socket.socket` instance.
1051
1052 .. note::
1053
1054 Note: this method should not be overloaded in subclassed
1055 event loops. For any custom exception handling, use
1056 :meth:`set_exception_handler()` method.
1057
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001058Enabling debug mode
1059^^^^^^^^^^^^^^^^^^^
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001060
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001061.. method:: loop.get_debug()
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001062
Victor Stinner7b7120e2014-06-23 00:12:14 +02001063 Get the debug mode (:class:`bool`) of the event loop.
1064
1065 The default value is ``True`` if the environment variable
1066 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
1067 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001068
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001069.. method:: loop.set_debug(enabled: bool)
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001070
1071 Set the debug mode of the event loop.
1072
1073.. seealso::
1074
Victor Stinner62511fd2014-06-23 00:36:11 +02001075 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001076
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001077
1078Running Subprocesses
1079^^^^^^^^^^^^^^^^^^^^
1080
1081Methods described in this subsections are low-level. In an
1082async/await code consider using high-level convenient
1083:func:`asyncio.create_subprocess_shell` and
1084:func:`asyncio.create_subprocess_exec` functions instead.
1085
1086.. note::
1087
1088 The default event loop that asyncio is pre-configured
1089 to use on **Windows** does not support subprocesses.
1090 See :ref:`Subprocess Support on Windows <asyncio-windows-subprocess>`
1091 for details.
1092
1093.. coroutinemethod:: loop.subprocess_exec(protocol_factory, \*args, \
1094 stdin=subprocess.PIPE, stdout=subprocess.PIPE, \
1095 stderr=subprocess.PIPE, \*\*kwargs)
1096
1097 Create a subprocess from one or more string arguments specified by
1098 *args*.
1099
1100 *args* must be a list of strings represented by:
1101
1102 * :class:`str`;
1103 * or :class:`bytes`, encoded to the
1104 :ref:`filesystem encoding <filesystem-encoding>`.
1105
1106 The first string specifies the program to execute,
1107 and the remaining strings specify the arguments. Together string
1108 arguments form the ``argv`` of the program.
1109
1110 This is similar to the standard library :class:`subprocess.Popen`
1111 class called with ``shell=False`` and the list of strings passed as
1112 the first argument; however, where :class:`~subprocess.Popen` takes
1113 a single argument which is list of strings, *subprocess_exec*
1114 takes multiple string arguments.
1115
1116 The *protocol_factory* must instantiate a subclass of the
1117 :class:`asyncio.SubprocessProtocol` class.
1118
1119 Other parameters:
1120
1121 * *stdin*: either a file-like object representing a pipe to be
1122 connected to the subprocess's standard input stream using
1123 :meth:`~loop.connect_write_pipe`, or the
1124 :const:`subprocess.PIPE` constant (default). By default a new
1125 pipe will be created and connected.
1126
1127 * *stdout*: either a file-like object representing the pipe to be
1128 connected to the subprocess's standard output stream using
1129 :meth:`~loop.connect_read_pipe`, or the
1130 :const:`subprocess.PIPE` constant (default). By default a new pipe
1131 will be created and connected.
1132
1133 * *stderr*: either a file-like object representing the pipe to be
1134 connected to the subprocess's standard error stream using
1135 :meth:`~loop.connect_read_pipe`, or one of
1136 :const:`subprocess.PIPE` (default) or :const:`subprocess.STDOUT`
1137 constants.
1138
1139 By default a new pipe will be created and connected. When
1140 :const:`subprocess.STDOUT` is specified, the subprocess' standard
1141 error stream will be connected to the same pipe as the standard
1142 output stream.
1143
1144 * All other keyword arguments are passed to :class:`subprocess.Popen`
1145 without interpretation, except for *bufsize*, *universal_newlines*
1146 and *shell*, which should not be specified at all.
1147
1148 See the constructor of the :class:`subprocess.Popen` class
1149 for documentation on other arguments.
1150
1151 Returns a pair of ``(transport, protocol)``, where *transport*
1152 conforms to the :class:`asyncio.SubprocessTransport` base class.
1153
1154.. coroutinemethod:: loop.subprocess_shell(protocol_factory, cmd, \*, \
1155 stdin=subprocess.PIPE, stdout=subprocess.PIPE, \
1156 stderr=subprocess.PIPE, \*\*kwargs)
1157
1158 Create a subprocess from *cmd*, which can be a :class:`str` or a
1159 :class:`bytes` string encoded to the
1160 :ref:`filesystem encoding <filesystem-encoding>`,
1161 using the platform's "shell" syntax.
1162
1163 This is similar to the standard library :class:`subprocess.Popen`
1164 class called with ``shell=True``.
1165
1166 The *protocol_factory* must instantiate a subclass of the
1167 :class:`SubprocessProtocol` class.
1168
1169 See :meth:`~loop.subprocess_exec` for more details about
1170 the remaining arguments.
1171
1172 Returns a pair of ``(transport, protocol)``, where *transport*
1173 conforms to the :class:`SubprocessTransport` base class.
1174
1175.. note::
1176 It is the application's responsibility to ensure that all whitespace
1177 and metacharacters are quoted appropriately to avoid `shell injection
1178 <https://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_
1179 vulnerabilities. The :func:`shlex.quote` function can be used to
1180 properly escape whitespace and shell metacharacters in strings that
1181 are going to be used to construct shell commands.
1182
1183
1184Callback Handles
1185================
1186
1187.. class:: Handle
1188
1189 A callback wrapper object returned by :meth:`loop.call_soon`,
1190 :meth:`loop.call_soon_threadsafe`.
1191
1192 .. method:: cancel()
1193
1194 Cancel the call. If the callback is already canceled or executed,
1195 this method has no effect.
1196
1197 .. method:: cancelled()
1198
1199 Return ``True`` if the call was cancelled.
1200
1201 .. versionadded:: 3.7
1202
1203.. class:: TimerHandle
1204
1205 A callback wrapper object returned by :meth:`loop.call_later`,
1206 and :meth:`loop.call_at`.
1207
1208 The class is inherited from :class:`Handle`.
1209
1210 .. method:: when()
1211
1212 Return a scheduled callback time as :class:`float` seconds.
1213
1214 The time is an absolute timestamp, using the same time
1215 reference as :meth:`loop.time`.
1216
1217 .. versionadded:: 3.7
1218
1219
1220Server Objects
1221==============
1222
1223Server objects are created by :meth:`loop.create_server`,
1224:meth:`loop.create_unix_server`, :func:`start_server`,
1225and :func:`start_unix_server` functions.
1226
1227Do not instantiate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +01001228
Victor Stinner8ebeb032014-07-11 23:47:40 +02001229.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +01001230
Yury Selivanovc9070d02018-01-25 18:08:09 -05001231 *Server* objects are asynchronous context managers. When used in an
1232 ``async with`` statement, it's guaranteed that the Server object is
1233 closed and not accepting new connections when the ``async with``
1234 statement is completed::
1235
1236 srv = await loop.create_server(...)
1237
1238 async with srv:
1239 # some code
1240
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001241 # At this point, srv is closed and no longer accepts new
1242 connections.
Yury Selivanovc9070d02018-01-25 18:08:09 -05001243
1244
1245 .. versionchanged:: 3.7
1246 Server object is an asynchronous context manager since Python 3.7.
Victor Stinner8c462c52014-01-24 18:11:43 +01001247
1248 .. method:: close()
1249
Victor Stinner4bfb14a2014-07-12 03:20:24 +02001250 Stop serving: close listening sockets and set the :attr:`sockets`
1251 attribute to ``None``.
1252
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001253 The sockets that represent existing incoming client connections
1254 are left open.
Victor Stinner8ebeb032014-07-11 23:47:40 +02001255
Berker Peksag49c9edf2016-01-20 07:14:22 +02001256 The server is closed asynchronously, use the :meth:`wait_closed`
1257 coroutine to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +01001258
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +05301259 .. method:: get_loop()
1260
1261 Gives the event loop associated with the server object.
1262
1263 .. versionadded:: 3.7
1264
Yury Selivanovc9070d02018-01-25 18:08:09 -05001265 .. coroutinemethod:: start_serving()
1266
1267 Start accepting connections.
1268
1269 This method is idempotent, so it can be called when
1270 the server is already being serving.
1271
1272 The new *start_serving* keyword-only parameter to
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001273 :meth:`loop.create_server` and
Yury Selivanovc9070d02018-01-25 18:08:09 -05001274 :meth:`asyncio.start_server` allows to create a Server object
1275 that is not accepting connections right away. In which case
1276 this method, or :meth:`Server.serve_forever` can be used
1277 to make the Server object to start accepting connections.
1278
1279 .. versionadded:: 3.7
1280
1281 .. coroutinemethod:: serve_forever()
1282
1283 Start accepting connections until the coroutine is cancelled.
1284 Cancellation of ``serve_forever`` task causes the server
1285 to be closed.
1286
1287 This method can be called if the server is already accepting
1288 connections. Only one ``serve_forever`` task can exist per
1289 one *Server* object.
1290
1291 Example::
1292
1293 async def client_connected(reader, writer):
1294 # Communicate with the client with
1295 # reader/writer streams. For example:
1296 await reader.readline()
1297
1298 async def main(host, port):
1299 srv = await asyncio.start_server(
1300 client_connected, host, port)
Andrew Svetlov17ab8f02018-02-17 19:44:35 +02001301 await srv.serve_forever()
Yury Selivanovc9070d02018-01-25 18:08:09 -05001302
1303 asyncio.run(main('127.0.0.1', 0))
1304
1305 .. versionadded:: 3.7
1306
1307 .. method:: is_serving()
1308
1309 Return ``True`` if the server is accepting new connections.
1310
1311 .. versionadded:: 3.7
1312
Victor Stinnerbdd574d2015-02-12 22:49:18 +01001313 .. coroutinemethod:: wait_closed()
Victor Stinner8c462c52014-01-24 18:11:43 +01001314
Victor Stinner8ebeb032014-07-11 23:47:40 +02001315 Wait until the :meth:`close` method completes.
1316
Victor Stinner8ebeb032014-07-11 23:47:40 +02001317 .. attribute:: sockets
1318
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001319 List of :class:`socket.socket` objects the server is listening to,
1320 or ``None`` if the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +01001321
Yury Selivanovc9070d02018-01-25 18:08:09 -05001322 .. versionchanged:: 3.7
1323 Prior to Python 3.7 ``Server.sockets`` used to return the
1324 internal list of server's sockets directly. In 3.7 a copy
1325 of that list is returned.
1326
Victor Stinner8c462c52014-01-24 18:11:43 +01001327
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001328.. _asyncio-event-loops:
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001329
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001330Event Loops Implementations
1331===========================
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001332
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001333asyncio ships with two different event loop implementations:
1334:class:`SelectorEventLoop` and :class:`ProactorEventLoop`.
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001335
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001336By default asyncio is configured to use :class:`SelectorEventLoop`
1337on all platforms.
Andrew Svetlov3d4dbd82018-02-01 19:59:32 +02001338
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001339
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001340.. class:: SelectorEventLoop
1341
1342 An event loop based on the :mod:`selectors` module.
1343
1344 Uses the most efficient *selector* available for the given
1345 platform. It is also possible to manually configure what
1346 exact selector implementation should be used::
1347
1348 import asyncio
1349 import selectors
1350
1351 selector = selectors.SelectSelector()
1352 loop = asyncio.SelectorEventLoop(selector)
1353 asyncio.set_event_loop(loop)
Andrew Svetlov7464e872018-01-19 20:04:29 +02001354
1355
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001356 Availability: UNIX, Windows.
Andrew Svetlov7464e872018-01-19 20:04:29 +02001357
1358
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001359.. class:: ProactorEventLoop
1360
1361 An event loop for Windows that uses "I/O Completion Ports" (IOCP).
1362
1363 Availability: Windows.
1364
1365 An example how to use :class:`ProactorEventLoop` on Windows::
1366
1367 import asyncio
1368 import sys
1369
1370 if sys.platform == 'win32':
1371 loop = asyncio.ProactorEventLoop()
1372 asyncio.set_event_loop(loop)
1373
1374 .. seealso::
1375
1376 `MSDN documentation on I/O Completion Ports
1377 <https://docs.microsoft.com/en-ca/windows/desktop/FileIO/i-o-completion-ports>`_.
1378
1379
1380.. class:: AbstractEventLoop
1381
1382 Abstract base class for asyncio-compliant event loops.
1383
1384 The :ref:`Event Loop Methods <asyncio-event-loop>` section lists all
1385 methods that an alternative implementation of ``AbstractEventLoop``
1386 should have defined.
1387
1388
1389Examples
1390========
1391
1392Note that all examples in this section **purposefully** show how
1393to use low-level event loop APIs such as :meth:`loop.run_forever`
1394and :meth:`loop.call_soon`. Modern asyncio applications rarely
1395need to be written this way; consider using high-level functions
1396like :func:`asyncio.run`.
1397
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001398
Victor Stinner3e09e322013-12-03 01:22:06 +01001399.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +01001400
Victor Stinner7f314ed2014-10-15 18:49:16 +02001401Hello World with call_soon()
Victor Stinnera092a612015-01-09 15:58:41 +01001402^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +01001403
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001404An example using the :meth:`loop.call_soon` method to schedule a
1405callback. The callback displays ``"Hello World"`` and then stops the
1406event loop::
Victor Stinnerea3183f2013-12-03 01:08:00 +01001407
1408 import asyncio
1409
Victor Stinner7f314ed2014-10-15 18:49:16 +02001410 def hello_world(loop):
Victor Stinnerea3183f2013-12-03 01:08:00 +01001411 print('Hello World')
Victor Stinner7f314ed2014-10-15 18:49:16 +02001412 loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +01001413
1414 loop = asyncio.get_event_loop()
Victor Stinner7f314ed2014-10-15 18:49:16 +02001415
1416 # Schedule a call to hello_world()
1417 loop.call_soon(hello_world, loop)
1418
1419 # Blocking call interrupted by loop.stop()
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001420 try:
1421 loop.run_forever()
1422 finally:
1423 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +01001424
Victor Stinner3e09e322013-12-03 01:22:06 +01001425.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +01001426
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001427 A similar :ref:`Hello World <asyncio-hello-world-coroutine>`
1428 example created with a coroutine and the :func:`run` function.
Victor Stinnerea3183f2013-12-03 01:08:00 +01001429
Victor Stinner8b863482014-01-27 10:07:50 +01001430
Victor Stinner7f314ed2014-10-15 18:49:16 +02001431.. _asyncio-date-callback:
1432
1433Display the current date with call_later()
Victor Stinnera092a612015-01-09 15:58:41 +01001434^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner7f314ed2014-10-15 18:49:16 +02001435
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001436An example of callback displaying the current date every second. The
1437callback uses the :meth:`loop.call_later` method to reschedule itself
1438during 5 seconds, and then stops the event loop::
Victor Stinner7f314ed2014-10-15 18:49:16 +02001439
1440 import asyncio
1441 import datetime
1442
1443 def display_date(end_time, loop):
1444 print(datetime.datetime.now())
1445 if (loop.time() + 1.0) < end_time:
1446 loop.call_later(1, display_date, end_time, loop)
1447 else:
1448 loop.stop()
1449
1450 loop = asyncio.get_event_loop()
1451
1452 # Schedule the first call to display_date()
1453 end_time = loop.time() + 5.0
1454 loop.call_soon(display_date, end_time, loop)
1455
1456 # Blocking call interrupted by loop.stop()
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001457 try:
1458 loop.run_forever()
1459 finally:
1460 loop.close()
Victor Stinner7f314ed2014-10-15 18:49:16 +02001461
1462.. seealso::
1463
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001464 A similar :ref:`current date <asyncio-date-coroutine>` example
1465 created with a coroutine and the :func:`run` function.
Victor Stinner7f314ed2014-10-15 18:49:16 +02001466
1467
Victor Stinner04e6df32014-10-11 16:16:27 +02001468.. _asyncio-watch-read-event:
Victor Stinner8b863482014-01-27 10:07:50 +01001469
Victor Stinner04e6df32014-10-11 16:16:27 +02001470Watch a file descriptor for read events
Victor Stinnera092a612015-01-09 15:58:41 +01001471^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +02001472
1473Wait until a file descriptor received some data using the
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001474:meth:`loop.add_reader` method and then close the event loop::
Victor Stinner04e6df32014-10-11 16:16:27 +02001475
1476 import asyncio
Victor Stinnerac577d72017-11-28 21:33:20 +01001477 from socket import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +02001478
1479 # Create a pair of connected file descriptors
Victor Stinnerccd8e342014-10-11 16:30:02 +02001480 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +02001481 loop = asyncio.get_event_loop()
1482
1483 def reader():
1484 data = rsock.recv(100)
1485 print("Received:", data.decode())
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001486
Victor Stinner2cef3002014-10-23 22:38:46 +02001487 # We are done: unregister the file descriptor
Victor Stinner04e6df32014-10-11 16:16:27 +02001488 loop.remove_reader(rsock)
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001489
Victor Stinner04e6df32014-10-11 16:16:27 +02001490 # Stop the event loop
1491 loop.stop()
1492
Victor Stinner2cef3002014-10-23 22:38:46 +02001493 # Register the file descriptor for read event
Victor Stinner04e6df32014-10-11 16:16:27 +02001494 loop.add_reader(rsock, reader)
1495
1496 # Simulate the reception of data from the network
1497 loop.call_soon(wsock.send, 'abc'.encode())
1498
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001499 try:
1500 # Run the event loop
1501 loop.run_forever()
1502 finally:
1503 # We are done, close sockets and the event loop
1504 rsock.close()
1505 wsock.close()
1506 loop.close()
Victor Stinner04e6df32014-10-11 16:16:27 +02001507
1508.. seealso::
1509
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001510 * A similar :ref:`example <asyncio-register-socket>`
1511 using transports, protocols, and the
1512 :meth:`loop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +02001513
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001514 * Another similar :ref:`example <asyncio-register-socket-streams>`
1515 using the high-level :func:`asyncio.open_connection` function
1516 and streams.
Victor Stinner04e6df32014-10-11 16:16:27 +02001517
1518
1519Set signal handlers for SIGINT and SIGTERM
Victor Stinnera092a612015-01-09 15:58:41 +01001520^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +02001521
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001522(This example only works on UNIX.)
1523
1524Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`
1525using the :meth:`loop.add_signal_handler` method::
Victor Stinner8b863482014-01-27 10:07:50 +01001526
1527 import asyncio
1528 import functools
1529 import os
1530 import signal
1531
1532 def ask_exit(signame):
1533 print("got signal %s: exit" % signame)
1534 loop.stop()
1535
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001536 async def main():
1537 loop = asyncio.get_running_loop()
Victor Stinner8b863482014-01-27 10:07:50 +01001538
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001539 for signame in {'SIGINT', 'SIGTERM'}:
1540 loop.add_signal_handler(
1541 getattr(signal, signame),
1542 functools.partial(ask_exit, signame))
Victor Stinner2cef3002014-10-23 22:38:46 +02001543
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001544 await asyncio.sleep(3600)
1545
1546 print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
1547 print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")
1548
1549 asyncio.run(main())