blob: 0320d798c1e594e6f994cb1dea291f2b2494ffc8 [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
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040011The event loop is the core 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
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040015Application developers should typically use the high-level asyncio functions,
16such as :func:`asyncio.run`, and should rarely need to reference the loop
17object or call its methods. This section is intended mostly for authors
18of lower-level code, libraries, and frameworks, who need finer control over
19the event loop behavior.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070020
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040021.. rubric:: Obtaining the Event Loop
Yury Selivanov7c7605f2018-09-11 09:54:40 -070022
23The following low-level functions can be used to get, set, or create
24an event loop:
25
26.. function:: get_running_loop()
27
28 Return the running event loop in the current OS thread.
29
30 If there is no running event loop a :exc:`RuntimeError` is raised.
31 This function can only be called from a coroutine or a callback.
32
33 .. versionadded:: 3.7
34
35.. function:: get_event_loop()
36
37 Get the current event loop. If there is no current event loop set
38 in the current OS thread and :func:`set_event_loop` has not yet
39 been called, asyncio will create a new event loop and set it as the
40 current one.
41
Carol Willing5b7cbd62018-09-12 17:05:17 -070042 Because this function has rather complex behavior (especially
43 when custom event loop policies are in use), using the
44 :func:`get_running_loop` function is preferred to :func:`get_event_loop`
45 in coroutines and callbacks.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070046
Carol Willing5b7cbd62018-09-12 17:05:17 -070047 Consider also using the :func:`asyncio.run` function instead of using
48 lower level functions to manually create and close an event loop.
Yury Selivanov7c7605f2018-09-11 09:54:40 -070049
50.. function:: set_event_loop(loop)
51
52 Set *loop* as a current event loop for the current OS thread.
53
54.. function:: new_event_loop()
55
56 Create a new event loop object.
57
58Note that the behaviour of :func:`get_event_loop`, :func:`set_event_loop`,
59and :func:`new_event_loop` functions can be altered by
60:ref:`setting a custom event loop policy <asyncio-policies>`.
61
62
63.. rubric:: Contents
64
65This documentation page contains the following sections:
66
Carol Willing5b7cbd62018-09-12 17:05:17 -070067* The `Event Loop Methods`_ section is the reference documentation of
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040068 the event loop APIs;
Yury Selivanov7c7605f2018-09-11 09:54:40 -070069
70* The `Callback Handles`_ section documents the :class:`Handle` and
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040071 :class:`TimerHandle` instances which are returned from scheduling
72 methods such as :meth:`loop.call_soon` and :meth:`loop.call_later`;
Yury Selivanov7c7605f2018-09-11 09:54:40 -070073
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040074* The `Server Objects`_ section documents types returned from
Yury Selivanov7c7605f2018-09-11 09:54:40 -070075 event loop methods like :meth:`loop.create_server`;
76
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -040077* The `Event Loop Implementations`_ section documents the
Yury Selivanov7c7605f2018-09-11 09:54:40 -070078 :class:`SelectorEventLoop` and :class:`ProactorEventLoop` classes;
79
80* The `Examples`_ section showcases how to work with some event
81 loop APIs.
82
83
Victor Stinner9592edb2014-02-02 15:03:02 +010084.. _asyncio-event-loop:
Victor Stinnerea3183f2013-12-03 01:08:00 +010085
Yury Selivanov7c7605f2018-09-11 09:54:40 -070086Event Loop Methods
87==================
Victor Stinnerea3183f2013-12-03 01:08:00 +010088
Carol Willing5b7cbd62018-09-12 17:05:17 -070089Event loops have **low-level** APIs for the following:
lf627d2c82017-07-25 17:03:51 -060090
Yury Selivanov7c7605f2018-09-11 09:54:40 -070091.. contents::
92 :depth: 1
93 :local:
Victor Stinnerea3183f2013-12-03 01:08:00 +010094
Victor Stinnerea3183f2013-12-03 01:08:00 +010095
Yury Selivanov7c7605f2018-09-11 09:54:40 -070096Running and stopping the loop
97^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +010098
Yury Selivanov7c7605f2018-09-11 09:54:40 -070099.. method:: loop.run_until_complete(future)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100100
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400101 Run until the *future* (an instance of :class:`Future`) has
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700102 completed.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100103
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700104 If the argument is a :ref:`coroutine object <coroutine>` it
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400105 is implicitly scheduled to run as a :class:`asyncio.Task`.
Eli Bendersky136fea22014-02-09 06:55:58 -0800106
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700107 Return the Future's result or raise its exception.
Guido van Rossumf68afd82016-08-08 09:41:21 -0700108
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700109.. method:: loop.run_forever()
Guido van Rossumf68afd82016-08-08 09:41:21 -0700110
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700111 Run the event loop until :meth:`stop` is called.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100112
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700113 If :meth:`stop` is called before :meth:`run_forever()` is called,
114 the loop will poll the I/O selector once with a timeout of zero,
115 run all callbacks scheduled in response to I/O events (and
116 those that were already scheduled), and then exit.
Victor Stinner83704962015-02-25 14:24:15 +0100117
Guido van Rossum41f69f42015-11-19 13:28:47 -0800118 If :meth:`stop` is called while :meth:`run_forever` is running,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700119 the loop will run the current batch of callbacks and then exit.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400120 Note that new callbacks scheduled by callbacks will not run in this
Carol Willing5b7cbd62018-09-12 17:05:17 -0700121 case; instead, they will run the next time :meth:`run_forever` or
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700122 :meth:`run_until_complete` is called.
Guido van Rossum41f69f42015-11-19 13:28:47 -0800123
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700124.. method:: loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100125
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700126 Stop the event loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100127
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700128.. method:: loop.is_running()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100129
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700130 Return ``True`` if the event loop is currently running.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100131
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700132.. method:: loop.is_closed()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100133
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700134 Return ``True`` if the event loop was closed.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100135
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700136.. method:: loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100137
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700138 Close the event loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100139
Carol Willing5b7cbd62018-09-12 17:05:17 -0700140 The loop must be running when this function is called.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700141 Any pending callbacks will be discarded.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100142
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700143 This method clears all queues and shuts down the executor, but does
144 not wait for the executor to finish.
Guido van Rossum41f69f42015-11-19 13:28:47 -0800145
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700146 This method is idempotent and irreversible. No other methods
147 should be called after the event loop is closed.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100148
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700149.. coroutinemethod:: loop.shutdown_asyncgens()
Yury Selivanov03660042016-12-15 17:36:05 -0500150
151 Schedule all currently open :term:`asynchronous generator` objects to
152 close with an :meth:`~agen.aclose()` call. After calling this method,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700153 the event loop will issue a warning if a new asynchronous generator
Carol Willing5b7cbd62018-09-12 17:05:17 -0700154 is iterated. This should be used to reliably finalize all scheduled
155 asynchronous generators, e.g.::
156
Yury Selivanov03660042016-12-15 17:36:05 -0500157
158 try:
159 loop.run_forever()
160 finally:
161 loop.run_until_complete(loop.shutdown_asyncgens())
162 loop.close()
163
164 .. versionadded:: 3.6
165
166
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700167Scheduling callbacks
168^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100169
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700170.. method:: loop.call_soon(callback, *args, context=None)
Victor Stinner8464c242014-11-28 13:15:41 +0100171
Carol Willing5b7cbd62018-09-12 17:05:17 -0700172 Schedule a *callback* to be called with *args* arguments at
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700173 the next iteration of the event loop.
Victor Stinner8464c242014-11-28 13:15:41 +0100174
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700175 Callbacks are called in the order in which they are registered.
176 Each callback will be called exactly once.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100177
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700178 An optional keyword-only *context* argument allows specifying a
179 custom :class:`contextvars.Context` for the *callback* to run in.
180 The current context is used when no *context* is provided.
Yury Selivanov28b91782018-05-23 13:35:04 -0400181
Yury Selivanov1096f762015-06-25 13:49:52 -0400182 An instance of :class:`asyncio.Handle` is returned, which can be
Carol Willing5b7cbd62018-09-12 17:05:17 -0700183 used later to cancel the callback.
184
185 This method is not thread-safe.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500186
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700187.. method:: loop.call_soon_threadsafe(callback, *args, context=None)
Victor Stinner8464c242014-11-28 13:15:41 +0100188
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700189 A thread-safe variant of :meth:`call_soon`. Must be used to
190 schedule callbacks *from another thread*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100191
Victor Stinner83704962015-02-25 14:24:15 +0100192 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
193 section of the documentation.
194
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700195.. versionchanged:: 3.7
196 The *context* keyword-only parameter was added. See :pep:`567`
197 for more details.
198
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400199.. _asyncio-pass-keywords:
200
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700201.. note::
202
Carol Willing5b7cbd62018-09-12 17:05:17 -0700203 Most :mod:`asyncio` scheduling functions don't allow passing
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400204 keyword arguments. To do that, use :func:`functools.partial`::
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700205
Carol Willing5b7cbd62018-09-12 17:05:17 -0700206 # will schedule "print("Hello", flush=True)"
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700207 loop.call_soon(
208 functools.partial(print, "Hello", flush=True))
209
210 Using partial objects is usually more convenient than using lambdas,
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400211 as asyncio can render partial objects better in debug and error
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700212 messages.
Yury Selivanov28b91782018-05-23 13:35:04 -0400213
Victor Stinnerea3183f2013-12-03 01:08:00 +0100214
Victor Stinner45b27ed2014-02-01 02:36:43 +0100215.. _asyncio-delayed-calls:
216
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700217Scheduling delayed callbacks
218^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100219
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700220Event loop provides mechanisms to schedule callback functions
221to be called at some point in the future. Event loop uses monotonic
222clocks to track time.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100223
Victor Stinner45b27ed2014-02-01 02:36:43 +0100224
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700225.. method:: loop.call_later(delay, callback, *args, context=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100226
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700227 Schedule *callback* to be called after the given *delay*
228 number of seconds (can be either an int or a float).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100229
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700230 An instance of :class:`asyncio.TimerHandle` is returned which can
231 be used to cancel the callback.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100232
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700233 *callback* will be called exactly once. If two callbacks are
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400234 scheduled for exactly the same time, the order in which they
235 are called is undefined.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100236
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700237 The optional positional *args* will be passed to the callback when
238 it is called. If you want the callback to be called with keyword
239 arguments use :func:`functools.partial`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100240
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700241 An optional keyword-only *context* argument allows specifying a
242 custom :class:`contextvars.Context` for the *callback* to run in.
243 The current context is used when no *context* is provided.
Victor Stinner8464c242014-11-28 13:15:41 +0100244
Yury Selivanov28b91782018-05-23 13:35:04 -0400245 .. versionchanged:: 3.7
246 The *context* keyword-only parameter was added. See :pep:`567`
247 for more details.
248
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400249 .. versionchanged:: 3.8
250 In Python 3.7 and earlier with the default event loop implementation,
251 the *delay* could not exceed one day.
252 This has been fixed in Python 3.8.
253
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700254.. method:: loop.call_at(when, callback, *args, context=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100255
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700256 Schedule *callback* to be called at the given absolute timestamp
257 *when* (an int or a float), using the same time reference as
258 :meth:`loop.time`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100259
260 This method's behavior is the same as :meth:`call_later`.
261
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700262 An instance of :class:`asyncio.TimerHandle` is returned which can
263 be used to cancel the callback.
Victor Stinner8464c242014-11-28 13:15:41 +0100264
Yury Selivanov28b91782018-05-23 13:35:04 -0400265 .. versionchanged:: 3.7
266 The *context* keyword-only parameter was added. See :pep:`567`
267 for more details.
268
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400269 .. versionchanged:: 3.8
270 In Python 3.7 and earlier with the default event loop implementation,
271 the difference between *when* and the current time could not exceed
272 one day. This has been fixed in Python 3.8.
273
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700274.. method:: loop.time()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100275
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700276 Return the current time, as a :class:`float` value, according to
277 the event loop's internal monotonic clock.
278
279.. note::
280
281 Timeouts (relative *delay* or absolute *when*) should not
282 exceed one day.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100283
Victor Stinner3e09e322013-12-03 01:22:06 +0100284.. seealso::
285
286 The :func:`asyncio.sleep` function.
287
Victor Stinnerea3183f2013-12-03 01:08:00 +0100288
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700289Creating Futures and Tasks
290^^^^^^^^^^^^^^^^^^^^^^^^^^
Yury Selivanov950204d2016-05-16 16:23:00 -0400291
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700292.. method:: loop.create_future()
Yury Selivanov950204d2016-05-16 16:23:00 -0400293
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700294 Create an :class:`asyncio.Future` object attached to the event loop.
Yury Selivanov950204d2016-05-16 16:23:00 -0400295
Carol Willing5b7cbd62018-09-12 17:05:17 -0700296 This is the preferred way to create Futures in asyncio. This lets
297 third-party event loops provide alternative implementations of
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700298 the Future object (with better performance or instrumentation).
Yury Selivanov950204d2016-05-16 16:23:00 -0400299
300 .. versionadded:: 3.5.2
301
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700302.. method:: loop.create_task(coro, \*, name=None)
Yury Selivanov950204d2016-05-16 16:23:00 -0400303
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700304 Schedule the execution of a :ref:`coroutine`.
305 Return a :class:`Task` object.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200306
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700307 Third-party event loops can use their own subclass of :class:`Task`
308 for interoperability. In this case, the result type is a subclass
309 of :class:`Task`.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200310
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700311 If the *name* argument is provided and not ``None``, it is set as
312 the name of the task using :meth:`Task.set_name`.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200313
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300314 .. versionchanged:: 3.8
315 Added the ``name`` parameter.
316
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700317.. method:: loop.set_task_factory(factory)
Yury Selivanov71854612015-05-11 16:28:27 -0400318
319 Set a task factory that will be used by
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700320 :meth:`loop.create_task`.
Yury Selivanov71854612015-05-11 16:28:27 -0400321
322 If *factory* is ``None`` the default task factory will be set.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400323 Otherwise, *factory* must be a *callable* with the signature matching
324 ``(loop, coro)``, where *loop* is a reference to the active
325 event loop, and *coro* is a coroutine object. The callable
326 must return a :class:`asyncio.Future`-compatible object.
Yury Selivanov71854612015-05-11 16:28:27 -0400327
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700328.. method:: loop.get_task_factory()
Yury Selivanov71854612015-05-11 16:28:27 -0400329
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700330 Return a task factory or ``None`` if the default one is in use.
Yury Selivanov71854612015-05-11 16:28:27 -0400331
Victor Stinner530ef2f2014-07-08 12:39:10 +0200332
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700333Opening network connections
334^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100335
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700336.. coroutinemethod:: loop.create_connection(protocol_factory, \
337 host=None, port=None, \*, ssl=None, \
338 family=0, proto=0, flags=0, sock=None, \
339 local_addr=None, server_hostname=None, \
340 ssl_handshake_timeout=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100341
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700342 Open a streaming transport connection to a given
343 address specified by *host* and *port*.
344
345 The socket family can be either :py:data:`~socket.AF_INET` or
346 :py:data:`~socket.AF_INET6` depending on *host* (or the *family*
347 argument, if provided).
348
349 The socket type will be :py:data:`~socket.SOCK_STREAM`.
350
351 *protocol_factory* must be a callable returning an
352 :ref:`asyncio protocol <asyncio-protocol>` implementation.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100353
Yury Selivanov19a44f62017-12-14 20:53:26 -0500354 This method will try to establish the connection in the background.
355 When successful, it returns a ``(transport, protocol)`` pair.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100356
357 The chronological synopsis of the underlying operation is as follows:
358
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700359 #. The connection is established and a :ref:`transport <asyncio-transport>`
360 is created for it.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100361
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700362 #. *protocol_factory* is called without arguments and is expected to
363 return a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100364
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700365 #. The protocol instance is coupled with the transport by calling its
366 :meth:`~BaseProtocol.connection_made` method.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100367
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700368 #. A ``(transport, protocol)`` tuple is returned on success.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100369
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700370 The created transport is an implementation-dependent bidirectional
371 stream.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100372
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700373 Other arguments:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100374
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400375 * *ssl*: if given and not false, a 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
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400378 the transport; if *ssl* is :const:`True`, a default context returned
379 from :func:`ssl.create_default_context` is used.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100380
Berker Peksag9c1dba22014-09-28 00:00:58 +0300381 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100382
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400383 * *server_hostname* sets or overrides the hostname that the target
384 server's certificate will be matched against. Should only be passed
385 if *ssl* is not ``None``. By default the value of the *host* argument
Victor Stinnerea3183f2013-12-03 01:08:00 +0100386 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
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400389 risk, allowing for potential man-in-the-middle attacks).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100390
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
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400405 * *ssl_handshake_timeout* is (for a TLS connection) the time in seconds
406 to wait for the TLS 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
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400420 Added support for SSL/TLS in :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
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400465 Unix.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700466
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
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400470 and some Unixes. If the :py:data:`~socket.SO_REUSEPORT` constant is not
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700471 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
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400481 On Windows, with :class:`ProactorEventLoop`, this method is not supported.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200482
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
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400494 Create a 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
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400501 *path* is the name of a Unix domain socket and is required,
502 unless a *sock* parameter is specified. Abstract Unix sockets,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700503 :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
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400509 Availability: Unix.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100510
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
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400532 on *port* of the *host* 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
Bumsik Kim5cc583d2018-09-16 19:40:44 -0400538 * *protocol_factory* must be a callable returning a
539 :ref:`protocol <asyncio-protocol>` implementation.
540
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400541 * The *host* parameter can be set to several types which determine where
542 the server would be listening:
543
544 - If *host* is a string, the TCP server is bound to a single network
545 interface specified by *host*.
546
547 - If *host* is a sequence of strings, the TCP server is bound to all
548 network interfaces specified by the sequence.
549
550 - If *host* is an empty string or ``None``, all interfaces are
551 assumed and a list of multiple sockets will be returned (most likely
552 one for IPv4 and another one for IPv6).
Victor Stinner33f6abe2014-10-12 20:36:04 +0200553
554 * *family* can be set to either :data:`socket.AF_INET` or
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700555 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6.
Carol Willing5b7cbd62018-09-12 17:05:17 -0700556 If not set, the *family* will be determined from host name
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700557 (defaults to :data:`~socket.AF_UNSPEC`).
Victor Stinner33f6abe2014-10-12 20:36:04 +0200558
559 * *flags* is a bitmask for :meth:`getaddrinfo`.
560
561 * *sock* can optionally be specified in order to use a preexisting
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400562 socket object. If specified, *host* and *port* must not be specified.
Victor Stinner33f6abe2014-10-12 20:36:04 +0200563
564 * *backlog* is the maximum number of queued connections passed to
565 :meth:`~socket.socket.listen` (defaults to 100).
566
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400567 * *ssl* can be set to an :class:`~ssl.SSLContext` instance to enable
568 TLS over the accepted connections.
Victor Stinner33f6abe2014-10-12 20:36:04 +0200569
570 * *reuse_address* tells the kernel to reuse a local socket in
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700571 ``TIME_WAIT`` state, without waiting for its natural timeout to
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300572 expire. If not specified will automatically be set to ``True`` on
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400573 Unix.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100574
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700575 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
576 same port as other existing endpoints are bound to, so long as they all
577 set this flag when being created. This option is not supported on
578 Windows.
579
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400580 * *ssl_handshake_timeout* is (for a TLS server) the time in seconds to wait
581 for the TLS handshake to complete before aborting the connection.
Yury Selivanov96026432018-06-04 11:32:35 -0400582 ``60.0`` seconds if ``None`` (default).
Neil Aspinallf7686c12017-12-19 19:45:42 +0000583
Yury Selivanovc9070d02018-01-25 18:08:09 -0500584 * *start_serving* set to ``True`` (the default) causes the created server
585 to start accepting connections immediately. When set to ``False``,
586 the user should await on :meth:`Server.start_serving` or
587 :meth:`Server.serve_forever` to make the server to start accepting
588 connections.
589
Neil Aspinallf7686c12017-12-19 19:45:42 +0000590 .. versionadded:: 3.7
591
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700592 Added *ssl_handshake_timeout* and *start_serving* parameters.
593
594 .. versionchanged:: 3.6
595
596 The socket option :py:data:`~socket.TCP_NODELAY` is set by default
597 for all TCP connections.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000598
Victor Stinner60208a12015-09-15 22:41:52 +0200599 .. versionchanged:: 3.5
600
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400601 Added support for SSL/TLS in :class:`ProactorEventLoop`.
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100602
Victor Stinner7b58a2b2015-09-21 18:41:05 +0200603 .. versionchanged:: 3.5.1
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200604
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700605 The *host* parameter can be a sequence of strings.
606
607 .. seealso::
608
609 The :func:`start_server` function is a higher-level alternative API
610 that returns a pair of :class:`StreamReader` and :class:`StreamWriter`
611 that can be used in an async/await code.
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200612
Victor Stinnerea3183f2013-12-03 01:08:00 +0100613
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700614.. coroutinemethod:: loop.create_unix_server(protocol_factory, path=None, \
615 \*, sock=None, backlog=100, ssl=None, \
616 ssl_handshake_timeout=None, start_serving=True)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100617
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700618 Similar to :meth:`loop.create_server` but works with the
619 :py:data:`~socket.AF_UNIX` socket family.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100620
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400621 *path* is the name of a Unix domain socket, and is required,
622 unless a *sock* argument is provided. Abstract Unix sockets,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700623 :class:`str`, :class:`bytes`, and :class:`~pathlib.Path` paths
624 are supported.
Yury Selivanov423fd362017-11-20 17:26:28 -0500625
Bumsik Kim5cc583d2018-09-16 19:40:44 -0400626 See the documentation of the :meth:`loop.create_server` method
627 for information about arguments to this method.
628
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400629 Availability: Unix.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100630
Neil Aspinallf7686c12017-12-19 19:45:42 +0000631 .. versionadded:: 3.7
632
Elvis Pranskevichusc0d062f2018-06-08 11:36:00 -0400633 The *ssl_handshake_timeout* and *start_serving* parameters.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000634
Yury Selivanov423fd362017-11-20 17:26:28 -0500635 .. versionchanged:: 3.7
636
637 The *path* parameter can now be a :class:`~pathlib.Path` object.
638
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700639.. coroutinemethod:: loop.connect_accepted_socket(protocol_factory, \
640 sock, \*, ssl=None, ssl_handshake_timeout=None)
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500641
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700642 Wrap an already accepted connection into a transport/protocol pair.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500643
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700644 This method can be used by servers that accept connections outside
645 of asyncio but that use asyncio to handle them.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500646
647 Parameters:
648
Bumsik Kim5cc583d2018-09-16 19:40:44 -0400649 * *protocol_factory* must be a callable returning a
650 :ref:`protocol <asyncio-protocol>` implementation.
651
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700652 * *sock* is a preexisting socket object returned from
653 :meth:`socket.accept <socket.socket.accept>`.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500654
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700655 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over
656 the accepted connections.
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500657
Neil Aspinallf7686c12017-12-19 19:45:42 +0000658 * *ssl_handshake_timeout* is (for an SSL connection) the time in seconds to
659 wait for the SSL handshake to complete before aborting the connection.
Yury Selivanov96026432018-06-04 11:32:35 -0400660 ``60.0`` seconds if ``None`` (default).
Neil Aspinallf7686c12017-12-19 19:45:42 +0000661
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700662 Returns a ``(transport, protocol)`` pair.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100663
Neil Aspinallf7686c12017-12-19 19:45:42 +0000664 .. versionadded:: 3.7
665
666 The *ssl_handshake_timeout* parameter.
667
AraHaan431665b2017-11-21 11:06:26 -0500668 .. versionadded:: 3.5.3
669
670
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700671Transferring files
672^^^^^^^^^^^^^^^^^^
Andrew Svetlov7c684072018-01-27 21:22:47 +0200673
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700674.. coroutinemethod:: loop.sendfile(transport, file, \
675 offset=0, count=None, *, fallback=True)
Andrew Svetlov7c684072018-01-27 21:22:47 +0200676
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700677 Send a *file* over a *transport*. Return the total number of bytes
678 sent.
Andrew Svetlov7c684072018-01-27 21:22:47 +0200679
680 The method uses high-performance :meth:`os.sendfile` if available.
681
682 *file* must be a regular file object opened in binary mode.
683
684 *offset* tells from where to start reading the file. If specified,
685 *count* is the total number of bytes to transmit as opposed to
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400686 sending the file until EOF is reached. File position is always updated,
687 even when this method raises an error, and
688 :meth:`file.tell() <io.IOBase.tell>` can be used to obtain the actual
689 number of bytes sent.
Andrew Svetlov7c684072018-01-27 21:22:47 +0200690
691 *fallback* set to ``True`` makes asyncio to manually read and send
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700692 the file when the platform does not support the sendfile system call
Andrew Svetlov7c684072018-01-27 21:22:47 +0200693 (e.g. Windows or SSL socket on Unix).
694
695 Raise :exc:`SendfileNotAvailableError` if the system does not support
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400696 the *sendfile* syscall and *fallback* is ``False``.
Andrew Svetlov7c684072018-01-27 21:22:47 +0200697
698 .. versionadded:: 3.7
699
700
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500701TLS Upgrade
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700702^^^^^^^^^^^
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500703
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700704.. coroutinemethod:: loop.start_tls(transport, protocol, \
705 sslcontext, \*, server_side=False, \
706 server_hostname=None, ssl_handshake_timeout=None)
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500707
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700708 Upgrade an existing transport-based connection to TLS.
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500709
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700710 Return a new transport instance, that the *protocol* must start using
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500711 immediately after the *await*. The *transport* instance passed to
712 the *start_tls* method should never be used again.
713
714 Parameters:
715
716 * *transport* and *protocol* instances that methods like
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700717 :meth:`~loop.create_server` and
718 :meth:`~loop.create_connection` return.
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500719
720 * *sslcontext*: a configured instance of :class:`~ssl.SSLContext`.
721
722 * *server_side* pass ``True`` when a server-side connection is being
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700723 upgraded (like the one created by :meth:`~loop.create_server`).
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500724
725 * *server_hostname*: sets or overrides the host name that the target
726 server's certificate will be matched against.
727
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400728 * *ssl_handshake_timeout* is (for a TLS connection) the time in seconds to
729 wait for the TLS handshake to complete before aborting the connection.
Yury Selivanov96026432018-06-04 11:32:35 -0400730 ``60.0`` seconds if ``None`` (default).
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500731
732 .. versionadded:: 3.7
733
734
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700735Watching file descriptors
736^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerc1567df2014-02-08 23:22:58 +0100737
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700738.. method:: loop.add_reader(fd, callback, \*args)
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200739
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400740 Start monitoring the *fd* file descriptor for read availability and
741 invoke *callback* with the specified arguments once *fd* is available for
742 reading.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200743
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700744.. method:: loop.remove_reader(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100745
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400746 Stop monitoring the *fd* file descriptor for read availability.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100747
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700748.. method:: loop.add_writer(fd, callback, \*args)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100749
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400750 Start monitoring the *fd* file descriptor for write availability and
751 invoke *callback* with the specified arguments once *fd* is available for
752 writing.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100753
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700754 Use :func:`functools.partial` :ref:`to pass keywords
755 <asyncio-pass-keywords>` to *func*.
Victor Stinner8464c242014-11-28 13:15:41 +0100756
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700757.. method:: loop.remove_writer(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100758
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400759 Stop monitoring the *fd* file descriptor for write availability.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100760
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700761See also :ref:`Platform Support <asyncio-platform-support>` section
762for some limitations of these methods.
Victor Stinner04e6df32014-10-11 16:16:27 +0200763
Victor Stinnerc1567df2014-02-08 23:22:58 +0100764
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700765Working with socket objects directly
766^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerc1567df2014-02-08 23:22:58 +0100767
Carol Willing5b7cbd62018-09-12 17:05:17 -0700768In general, protocol implementations that use transport-based APIs
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700769such as :meth:`loop.create_connection` and :meth:`loop.create_server`
770are faster than implementations that work with sockets directly.
Carol Willing5b7cbd62018-09-12 17:05:17 -0700771However, there are some use cases when performance is not critical, and
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700772working with :class:`~socket.socket` objects directly is more
773convenient.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100774
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700775.. coroutinemethod:: loop.sock_recv(sock, nbytes)
Yury Selivanov55c50842016-06-08 12:48:15 -0400776
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400777 Receive up to *nbytes* from *sock*. Asynchronous version of
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700778 :meth:`socket.recv() <socket.socket.recv>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100779
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400780 Return the received data as a bytes object.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700781
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400782 *sock* must be a non-blocking socket.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200783
Yury Selivanov19a44f62017-12-14 20:53:26 -0500784 .. versionchanged:: 3.7
Carol Willing5b7cbd62018-09-12 17:05:17 -0700785 Even though this method was always documented as a coroutine
786 method, releases before Python 3.7 returned a :class:`Future`.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700787 Since Python 3.7 this is an ``async def`` method.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100788
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700789.. coroutinemethod:: loop.sock_recv_into(sock, buf)
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200790
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400791 Receive data from *sock* into the *buf* buffer. Modeled after the blocking
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700792 :meth:`socket.recv_into() <socket.socket.recv_into>` method.
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200793
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700794 Return the number of bytes written to the buffer.
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200795
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400796 *sock* must be a non-blocking socket.
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200797
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200798 .. versionadded:: 3.7
799
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700800.. coroutinemethod:: loop.sock_sendall(sock, data)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100801
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400802 Send *data* to the *sock* socket. Asynchronous version of
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700803 :meth:`socket.sendall() <socket.socket.sendall>`.
Yury Selivanov55c50842016-06-08 12:48:15 -0400804
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400805 This method continues to send to the socket until either all data
806 in *data* has been sent or an error occurs. ``None`` is returned
Carol Willing5b7cbd62018-09-12 17:05:17 -0700807 on success. On error, an exception is raised. Additionally, there is no way
808 to determine how much data, if any, was successfully processed by the
809 receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100810
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400811 *sock* must be a non-blocking socket.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200812
Yury Selivanov19a44f62017-12-14 20:53:26 -0500813 .. versionchanged:: 3.7
814 Even though the method was always documented as a coroutine
815 method, before Python 3.7 it returned an :class:`Future`.
816 Since Python 3.7, this is an ``async def`` method.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100817
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700818.. coroutinemethod:: loop.sock_connect(sock, address)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100819
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400820 Connect *sock* to a remote socket at *address*.
Victor Stinner1b0580b2014-02-13 09:24:37 +0100821
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700822 Asynchronous version of :meth:`socket.connect() <socket.socket.connect>`.
823
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400824 *sock* must be a non-blocking socket.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200825
Yury Selivanov55c50842016-06-08 12:48:15 -0400826 .. versionchanged:: 3.5.2
827 ``address`` no longer needs to be resolved. ``sock_connect``
828 will try to check if the *address* is already resolved by calling
829 :func:`socket.inet_pton`. If not,
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700830 :meth:`loop.getaddrinfo` will be used to resolve the
Yury Selivanov55c50842016-06-08 12:48:15 -0400831 *address*.
832
Victor Stinnerc1567df2014-02-08 23:22:58 +0100833 .. seealso::
834
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700835 :meth:`loop.create_connection`
Yury Selivanov55c50842016-06-08 12:48:15 -0400836 and :func:`asyncio.open_connection() <open_connection>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100837
838
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700839.. coroutinemethod:: loop.sock_accept(sock)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100840
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700841 Accept a connection. Modeled after the blocking
842 :meth:`socket.accept() <socket.socket.accept>` method.
Yury Selivanov55c50842016-06-08 12:48:15 -0400843
844 The socket must be bound to an address and listening
Victor Stinnerc1567df2014-02-08 23:22:58 +0100845 for connections. The return value is a pair ``(conn, address)`` where *conn*
846 is a *new* socket object usable to send and receive data on the connection,
847 and *address* is the address bound to the socket on the other end of the
848 connection.
849
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400850 *sock* must be a non-blocking socket.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200851
Yury Selivanov19a44f62017-12-14 20:53:26 -0500852 .. versionchanged:: 3.7
853 Even though the method was always documented as a coroutine
854 method, before Python 3.7 it returned a :class:`Future`.
855 Since Python 3.7, this is an ``async def`` method.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100856
857 .. seealso::
858
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700859 :meth:`loop.create_server` and :func:`start_server`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100860
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700861.. coroutinemethod:: loop.sock_sendfile(sock, file, offset=0, count=None, \
862 \*, fallback=True)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200863
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700864 Send a file using high-performance :mod:`os.sendfile` if possible.
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400865 Return the total number of bytes sent.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200866
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700867 Asynchronous version of :meth:`socket.sendfile() <socket.socket.sendfile>`.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200868
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400869 *sock* must be a non-blocking :const:`socket.SOCK_STREAM`
870 :class:`~socket.socket`.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200871
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400872 *file* must be a regular file object open in binary mode.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200873
874 *offset* tells from where to start reading the file. If specified,
875 *count* is the total number of bytes to transmit as opposed to
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400876 sending the file until EOF is reached. File position is always updated,
877 even when this method raises an error, and
878 :meth:`file.tell() <io.IOBase.tell>` can be used to obtain the actual
879 number of bytes sent.
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200880
Carol Willing5b7cbd62018-09-12 17:05:17 -0700881 *fallback*, when set to ``True``, makes asyncio manually read and send
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200882 the file when the platform does not support the sendfile syscall
883 (e.g. Windows or SSL socket on Unix).
884
Andrew Svetlov7464e872018-01-19 20:04:29 +0200885 Raise :exc:`SendfileNotAvailableError` if the system does not support
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200886 *sendfile* syscall and *fallback* is ``False``.
887
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400888 *sock* must be a non-blocking socket.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700889
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200890 .. versionadded:: 3.7
891
Victor Stinnerc1567df2014-02-08 23:22:58 +0100892
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700893DNS
894^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100895
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700896.. coroutinemethod:: loop.getaddrinfo(host, port, \*, family=0, \
897 type=0, proto=0, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100898
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700899 Asynchronous version of :meth:`socket.getaddrinfo`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100900
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700901.. coroutinemethod:: loop.getnameinfo(sockaddr, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100902
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700903 Asynchronous version of :meth:`socket.getnameinfo`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100904
Yury Selivanovbec23722018-01-28 14:09:40 -0500905.. versionchanged:: 3.7
906 Both *getaddrinfo* and *getnameinfo* methods were always documented
907 to return a coroutine, but prior to Python 3.7 they were, in fact,
908 returning :class:`asyncio.Future` objects. Starting with Python 3.7
909 both methods are coroutines.
910
Victor Stinnerea3183f2013-12-03 01:08:00 +0100911
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700912Working with pipes
913^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100914
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700915.. coroutinemethod:: loop.connect_read_pipe(protocol_factory, pipe)
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200916
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400917 Register the read end of *pipe* in the event loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100918
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700919 *protocol_factory* must be a callable returning an
920 :ref:`asyncio protocol <asyncio-protocol>` implementation.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100921
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700922 *pipe* is a :term:`file-like object <file object>`.
923
924 Return pair ``(transport, protocol)``, where *transport* supports
Bumsik Kim5cc583d2018-09-16 19:40:44 -0400925 the :class:`ReadTransport` interface and *protocol* is an object
926 instantiated by the *protocol_factory*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100927
Victor Stinnerd84fd732014-08-26 01:01:59 +0200928 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
929 non-blocking mode.
930
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700931.. coroutinemethod:: loop.connect_write_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100932
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400933 Register the write end of *pipe* in the event loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100934
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700935 *protocol_factory* must be a callable returning an
936 :ref:`asyncio protocol <asyncio-protocol>` implementation.
937
938 *pipe* is :term:`file-like object <file object>`.
939
Victor Stinner2cef3002014-10-23 22:38:46 +0200940 Return pair ``(transport, protocol)``, where *transport* supports
Bumsik Kim5cc583d2018-09-16 19:40:44 -0400941 :class:`WriteTransport` interface and *protocol* is an object
942 instantiated by the *protocol_factory*.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100943
Victor Stinnerd84fd732014-08-26 01:01:59 +0200944 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
945 non-blocking mode.
946
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700947.. note::
948
949 :class:`SelectorEventLoop` does not support the above methods on
Carol Willing5b7cbd62018-09-12 17:05:17 -0700950 Windows. Use :class:`ProactorEventLoop` instead for Windows.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700951
Victor Stinner08444382014-02-02 22:43:39 +0100952.. seealso::
953
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700954 The :meth:`loop.subprocess_exec` and
955 :meth:`loop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100956
Victor Stinnerea3183f2013-12-03 01:08:00 +0100957
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400958Unix signals
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700959^^^^^^^^^^^^
Victor Stinner8b863482014-01-27 10:07:50 +0100960
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700961.. method:: loop.add_signal_handler(signum, callback, \*args)
Victor Stinner8b863482014-01-27 10:07:50 +0100962
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400963 Set *callback* as the handler for the *signum* signal.
Victor Stinner8b863482014-01-27 10:07:50 +0100964
965 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
966 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
967
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700968 Use :func:`functools.partial` :ref:`to pass keywords
969 <asyncio-pass-keywords>` to *func*.
Victor Stinner8464c242014-11-28 13:15:41 +0100970
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700971.. method:: loop.remove_signal_handler(sig)
Victor Stinner8b863482014-01-27 10:07:50 +0100972
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400973 Remove the handler for the *sig* signal.
Victor Stinner8b863482014-01-27 10:07:50 +0100974
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400975 Return ``True`` if the signal handler was removed, or ``False`` if
976 no handler was set for the given signal.
Victor Stinner8b863482014-01-27 10:07:50 +0100977
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400978Availability: Unix.
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700979
Victor Stinner8b863482014-01-27 10:07:50 +0100980.. seealso::
981
982 The :mod:`signal` module.
983
984
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700985Executing code in thread or process pools
986^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100987
Yury Selivanov394374e2018-09-17 15:35:24 -0400988.. coroutinemethod:: loop.run_in_executor(executor, func, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100989
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -0400990 Arrange for *func* to be called in the specified executor.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100991
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700992 The *executor* argument should be an :class:`concurrent.futures.Executor`
Larry Hastings3732ed22014-03-15 21:13:56 -0700993 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100994
Yury Selivanov7c7605f2018-09-11 09:54:40 -0700995 Use :func:`functools.partial` :ref:`to pass keywords
996 <asyncio-pass-keywords>` to *func*.
Victor Stinner8464c242014-11-28 13:15:41 +0100997
Yury Selivanovbec23722018-01-28 14:09:40 -0500998 This method returns a :class:`asyncio.Future` object.
999
Yury Selivanove8a60452016-10-21 17:40:42 -04001000 .. versionchanged:: 3.5.3
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001001 :meth:`loop.run_in_executor` no longer configures the
Yury Selivanove8a60452016-10-21 17:40:42 -04001002 ``max_workers`` of the thread pool executor it creates, instead
1003 leaving it up to the thread pool executor
1004 (:class:`~concurrent.futures.ThreadPoolExecutor`) to set the
1005 default.
1006
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001007.. method:: loop.set_default_executor(executor)
Victor Stinnerea3183f2013-12-03 01:08:00 +01001008
Elvis Pranskevichus22d25082018-07-30 11:42:43 +01001009 Set *executor* as the default executor used by :meth:`run_in_executor`.
1010 *executor* should be an instance of
1011 :class:`~concurrent.futures.ThreadPoolExecutor`.
1012
1013 .. deprecated:: 3.8
1014 Using an executor that is not an instance of
1015 :class:`~concurrent.futures.ThreadPoolExecutor` is deprecated and
1016 will trigger an error in Python 3.9.
Victor Stinnerea3183f2013-12-03 01:08:00 +01001017
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001018 *executor* must be an instance of
1019 :class:`concurrent.futures.ThreadPoolExecutor`.
1020
Victor Stinnerea3183f2013-12-03 01:08:00 +01001021
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001022Error Handling API
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001023^^^^^^^^^^^^^^^^^^
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001024
Martin Panterc04fb562016-02-10 05:44:01 +00001025Allows customizing how exceptions are handled in the event loop.
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001026
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001027.. method:: loop.set_exception_handler(handler)
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001028
1029 Set *handler* as the new event loop exception handler.
1030
1031 If *handler* is ``None``, the default exception handler will
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001032 be set. Otherwise, *handler* must be a callable with the signature
1033 matching ``(loop, context)``, where ``loop``
1034 is a reference to the active event loop, and ``context``
1035 is a ``dict`` object containing the details of the exception
1036 (see :meth:`call_exception_handler` documentation for details
1037 about context).
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001038
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001039.. method:: loop.get_exception_handler()
Yury Selivanov950204d2016-05-16 16:23:00 -04001040
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001041 Return the current exception handler, or ``None`` if no custom
1042 exception handler was set.
Yury Selivanov950204d2016-05-16 16:23:00 -04001043
1044 .. versionadded:: 3.5.2
1045
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001046.. method:: loop.default_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001047
1048 Default exception handler.
1049
1050 This is called when an exception occurs and no exception
Carol Willing5b7cbd62018-09-12 17:05:17 -07001051 handler is set. This can be called by a custom exception
1052 handler that wants to defer to the default handler behavior.
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001053
1054 *context* parameter has the same meaning as in
1055 :meth:`call_exception_handler`.
1056
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001057.. method:: loop.call_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001058
1059 Call the current event loop exception handler.
1060
1061 *context* is a ``dict`` object containing the following keys
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001062 (new keys may be introduced in future Python versions):
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001063
1064 * 'message': Error message;
1065 * 'exception' (optional): Exception object;
1066 * 'future' (optional): :class:`asyncio.Future` instance;
1067 * 'handle' (optional): :class:`asyncio.Handle` instance;
1068 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
1069 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
1070 * 'socket' (optional): :class:`socket.socket` instance.
1071
1072 .. note::
1073
Carol Willing5b7cbd62018-09-12 17:05:17 -07001074 This method should not be overloaded in subclassed
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001075 event loops. For custom exception handling, use
1076 the :meth:`set_exception_handler()` method.
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001077
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001078Enabling debug mode
1079^^^^^^^^^^^^^^^^^^^
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001080
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001081.. method:: loop.get_debug()
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001082
Victor Stinner7b7120e2014-06-23 00:12:14 +02001083 Get the debug mode (:class:`bool`) of the event loop.
1084
1085 The default value is ``True`` if the environment variable
1086 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
1087 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001088
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001089.. method:: loop.set_debug(enabled: bool)
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001090
1091 Set the debug mode of the event loop.
1092
Yury Selivanov805e27e2018-09-14 16:57:11 -07001093 .. versionchanged:: 3.7
1094
1095 The new ``-X dev`` command line option can now also be used
1096 to enable the debug mode.
1097
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001098.. seealso::
1099
Victor Stinner62511fd2014-06-23 00:36:11 +02001100 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001101
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001102
1103Running Subprocesses
1104^^^^^^^^^^^^^^^^^^^^
1105
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001106Methods described in this subsections are low-level. In regular
1107async/await code consider using the high-level
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001108:func:`asyncio.create_subprocess_shell` and
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001109:func:`asyncio.create_subprocess_exec` convenience functions instead.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001110
1111.. note::
1112
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001113 The default asyncio event loop on **Windows** does not support
1114 subprocesses. See :ref:`Subprocess Support on Windows
1115 <asyncio-windows-subprocess>` for details.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001116
1117.. coroutinemethod:: loop.subprocess_exec(protocol_factory, \*args, \
1118 stdin=subprocess.PIPE, stdout=subprocess.PIPE, \
1119 stderr=subprocess.PIPE, \*\*kwargs)
1120
1121 Create a subprocess from one or more string arguments specified by
1122 *args*.
1123
1124 *args* must be a list of strings represented by:
1125
1126 * :class:`str`;
1127 * or :class:`bytes`, encoded to the
1128 :ref:`filesystem encoding <filesystem-encoding>`.
1129
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001130 The first string specifies the program executable,
Carol Willing5b7cbd62018-09-12 17:05:17 -07001131 and the remaining strings specify the arguments. Together, string
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001132 arguments form the ``argv`` of the program.
1133
1134 This is similar to the standard library :class:`subprocess.Popen`
1135 class called with ``shell=False`` and the list of strings passed as
1136 the first argument; however, where :class:`~subprocess.Popen` takes
1137 a single argument which is list of strings, *subprocess_exec*
1138 takes multiple string arguments.
1139
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001140 The *protocol_factory* must be a callable returning a subclass of the
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001141 :class:`asyncio.SubprocessProtocol` class.
1142
1143 Other parameters:
1144
1145 * *stdin*: either a file-like object representing a pipe to be
1146 connected to the subprocess's standard input stream using
1147 :meth:`~loop.connect_write_pipe`, or the
1148 :const:`subprocess.PIPE` constant (default). By default a new
1149 pipe will be created and connected.
1150
1151 * *stdout*: either a file-like object representing the pipe to be
1152 connected to the subprocess's standard output stream using
1153 :meth:`~loop.connect_read_pipe`, or the
1154 :const:`subprocess.PIPE` constant (default). By default a new pipe
1155 will be created and connected.
1156
1157 * *stderr*: either a file-like object representing the pipe to be
1158 connected to the subprocess's standard error stream using
1159 :meth:`~loop.connect_read_pipe`, or one of
1160 :const:`subprocess.PIPE` (default) or :const:`subprocess.STDOUT`
1161 constants.
1162
1163 By default a new pipe will be created and connected. When
1164 :const:`subprocess.STDOUT` is specified, the subprocess' standard
1165 error stream will be connected to the same pipe as the standard
1166 output stream.
1167
1168 * All other keyword arguments are passed to :class:`subprocess.Popen`
1169 without interpretation, except for *bufsize*, *universal_newlines*
1170 and *shell*, which should not be specified at all.
1171
1172 See the constructor of the :class:`subprocess.Popen` class
1173 for documentation on other arguments.
1174
1175 Returns a pair of ``(transport, protocol)``, where *transport*
Bumsik Kim5cc583d2018-09-16 19:40:44 -04001176 conforms to the :class:`asyncio.SubprocessTransport` base class and
1177 *protocol* is an object instantiated by the *protocol_factory*.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001178
1179.. coroutinemethod:: loop.subprocess_shell(protocol_factory, cmd, \*, \
1180 stdin=subprocess.PIPE, stdout=subprocess.PIPE, \
1181 stderr=subprocess.PIPE, \*\*kwargs)
1182
1183 Create a subprocess from *cmd*, which can be a :class:`str` or a
1184 :class:`bytes` string encoded to the
1185 :ref:`filesystem encoding <filesystem-encoding>`,
1186 using the platform's "shell" syntax.
1187
1188 This is similar to the standard library :class:`subprocess.Popen`
1189 class called with ``shell=True``.
1190
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001191 The *protocol_factory* must be a callable returning a subclass of the
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001192 :class:`SubprocessProtocol` class.
1193
1194 See :meth:`~loop.subprocess_exec` for more details about
1195 the remaining arguments.
1196
1197 Returns a pair of ``(transport, protocol)``, where *transport*
Bumsik Kim5cc583d2018-09-16 19:40:44 -04001198 conforms to the :class:`SubprocessTransport` base class and
1199 *protocol* is an object instantiated by the *protocol_factory*.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001200
1201.. note::
1202 It is the application's responsibility to ensure that all whitespace
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001203 and special characters are quoted appropriately to avoid `shell injection
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001204 <https://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_
1205 vulnerabilities. The :func:`shlex.quote` function can be used to
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001206 properly escape whitespace and special characters in strings that
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001207 are going to be used to construct shell commands.
1208
1209
1210Callback Handles
1211================
1212
1213.. class:: Handle
1214
1215 A callback wrapper object returned by :meth:`loop.call_soon`,
1216 :meth:`loop.call_soon_threadsafe`.
1217
1218 .. method:: cancel()
1219
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001220 Cancel the callback. If the callback has already been canceled
1221 or executed, this method has no effect.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001222
1223 .. method:: cancelled()
1224
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001225 Return ``True`` if the callback was cancelled.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001226
1227 .. versionadded:: 3.7
1228
1229.. class:: TimerHandle
1230
1231 A callback wrapper object returned by :meth:`loop.call_later`,
1232 and :meth:`loop.call_at`.
1233
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001234 This class is a subclass of :class:`Handle`.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001235
1236 .. method:: when()
1237
1238 Return a scheduled callback time as :class:`float` seconds.
1239
1240 The time is an absolute timestamp, using the same time
1241 reference as :meth:`loop.time`.
1242
1243 .. versionadded:: 3.7
1244
1245
1246Server Objects
1247==============
1248
1249Server objects are created by :meth:`loop.create_server`,
1250:meth:`loop.create_unix_server`, :func:`start_server`,
1251and :func:`start_unix_server` functions.
1252
1253Do not instantiate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +01001254
Victor Stinner8ebeb032014-07-11 23:47:40 +02001255.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +01001256
Yury Selivanovc9070d02018-01-25 18:08:09 -05001257 *Server* objects are asynchronous context managers. When used in an
1258 ``async with`` statement, it's guaranteed that the Server object is
1259 closed and not accepting new connections when the ``async with``
1260 statement is completed::
1261
1262 srv = await loop.create_server(...)
1263
1264 async with srv:
1265 # some code
1266
Carol Willing5b7cbd62018-09-12 17:05:17 -07001267 # At this point, srv is closed and no longer accepts new connections.
Yury Selivanovc9070d02018-01-25 18:08:09 -05001268
1269
1270 .. versionchanged:: 3.7
1271 Server object is an asynchronous context manager since Python 3.7.
Victor Stinner8c462c52014-01-24 18:11:43 +01001272
1273 .. method:: close()
1274
Victor Stinner4bfb14a2014-07-12 03:20:24 +02001275 Stop serving: close listening sockets and set the :attr:`sockets`
1276 attribute to ``None``.
1277
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001278 The sockets that represent existing incoming client connections
1279 are left open.
Victor Stinner8ebeb032014-07-11 23:47:40 +02001280
Berker Peksag49c9edf2016-01-20 07:14:22 +02001281 The server is closed asynchronously, use the :meth:`wait_closed`
1282 coroutine to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +01001283
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +05301284 .. method:: get_loop()
1285
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001286 Return the event loop associated with the server object.
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +05301287
1288 .. versionadded:: 3.7
1289
Yury Selivanovc9070d02018-01-25 18:08:09 -05001290 .. coroutinemethod:: start_serving()
1291
1292 Start accepting connections.
1293
1294 This method is idempotent, so it can be called when
1295 the server is already being serving.
1296
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001297 The *start_serving* keyword-only parameter to
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001298 :meth:`loop.create_server` and
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001299 :meth:`asyncio.start_server` allows creating a Server object
1300 that is not accepting connections initially. In this case
1301 ``Server.start_serving()``, or :meth:`Server.serve_forever` can be used
1302 to make the Server start accepting connections.
Yury Selivanovc9070d02018-01-25 18:08:09 -05001303
1304 .. versionadded:: 3.7
1305
1306 .. coroutinemethod:: serve_forever()
1307
1308 Start accepting connections until the coroutine is cancelled.
1309 Cancellation of ``serve_forever`` task causes the server
1310 to be closed.
1311
1312 This method can be called if the server is already accepting
1313 connections. Only one ``serve_forever`` task can exist per
1314 one *Server* object.
1315
1316 Example::
1317
1318 async def client_connected(reader, writer):
1319 # Communicate with the client with
1320 # reader/writer streams. For example:
1321 await reader.readline()
1322
1323 async def main(host, port):
1324 srv = await asyncio.start_server(
1325 client_connected, host, port)
Andrew Svetlov17ab8f02018-02-17 19:44:35 +02001326 await srv.serve_forever()
Yury Selivanovc9070d02018-01-25 18:08:09 -05001327
1328 asyncio.run(main('127.0.0.1', 0))
1329
1330 .. versionadded:: 3.7
1331
1332 .. method:: is_serving()
1333
1334 Return ``True`` if the server is accepting new connections.
1335
1336 .. versionadded:: 3.7
1337
Victor Stinnerbdd574d2015-02-12 22:49:18 +01001338 .. coroutinemethod:: wait_closed()
Victor Stinner8c462c52014-01-24 18:11:43 +01001339
Victor Stinner8ebeb032014-07-11 23:47:40 +02001340 Wait until the :meth:`close` method completes.
1341
Victor Stinner8ebeb032014-07-11 23:47:40 +02001342 .. attribute:: sockets
1343
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001344 List of :class:`socket.socket` objects the server is listening on,
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001345 or ``None`` if the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +01001346
Yury Selivanovc9070d02018-01-25 18:08:09 -05001347 .. versionchanged:: 3.7
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001348 Prior to Python 3.7 ``Server.sockets`` used to return an
1349 internal list of server sockets directly. In 3.7 a copy
Yury Selivanovc9070d02018-01-25 18:08:09 -05001350 of that list is returned.
1351
Victor Stinner8c462c52014-01-24 18:11:43 +01001352
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001353.. _asyncio-event-loops:
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001354
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001355Event Loop Implementations
1356==========================
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001357
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001358asyncio ships with two different event loop implementations:
1359:class:`SelectorEventLoop` and :class:`ProactorEventLoop`.
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001360
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001361By default asyncio is configured to use :class:`SelectorEventLoop`
1362on all platforms.
Andrew Svetlov3d4dbd82018-02-01 19:59:32 +02001363
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001364
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001365.. class:: SelectorEventLoop
1366
1367 An event loop based on the :mod:`selectors` module.
1368
1369 Uses the most efficient *selector* available for the given
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001370 platform. It is also possible to manually configure the
1371 exact selector implementation to be used::
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001372
1373 import asyncio
1374 import selectors
1375
1376 selector = selectors.SelectSelector()
1377 loop = asyncio.SelectorEventLoop(selector)
1378 asyncio.set_event_loop(loop)
Andrew Svetlov7464e872018-01-19 20:04:29 +02001379
1380
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001381 Availability: Unix, Windows.
Andrew Svetlov7464e872018-01-19 20:04:29 +02001382
1383
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001384.. class:: ProactorEventLoop
1385
1386 An event loop for Windows that uses "I/O Completion Ports" (IOCP).
1387
1388 Availability: Windows.
1389
1390 An example how to use :class:`ProactorEventLoop` on Windows::
1391
1392 import asyncio
1393 import sys
1394
1395 if sys.platform == 'win32':
1396 loop = asyncio.ProactorEventLoop()
1397 asyncio.set_event_loop(loop)
1398
1399 .. seealso::
1400
1401 `MSDN documentation on I/O Completion Ports
1402 <https://docs.microsoft.com/en-ca/windows/desktop/FileIO/i-o-completion-ports>`_.
1403
1404
1405.. class:: AbstractEventLoop
1406
1407 Abstract base class for asyncio-compliant event loops.
1408
1409 The :ref:`Event Loop Methods <asyncio-event-loop>` section lists all
1410 methods that an alternative implementation of ``AbstractEventLoop``
1411 should have defined.
1412
1413
1414Examples
1415========
1416
1417Note that all examples in this section **purposefully** show how
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001418to use the low-level event loop APIs, such as :meth:`loop.run_forever`
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001419and :meth:`loop.call_soon`. Modern asyncio applications rarely
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001420need to be written this way; consider using the high-level functions
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001421like :func:`asyncio.run`.
1422
Yury Selivanov43ee1c12014-02-19 20:58:44 -05001423
Yury Selivanov394374e2018-09-17 15:35:24 -04001424.. _asyncio_example_lowlevel_helloworld:
Victor Stinnerea3183f2013-12-03 01:08:00 +01001425
Victor Stinner7f314ed2014-10-15 18:49:16 +02001426Hello World with call_soon()
Victor Stinnera092a612015-01-09 15:58:41 +01001427^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +01001428
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001429An example using the :meth:`loop.call_soon` method to schedule a
1430callback. The callback displays ``"Hello World"`` and then stops the
1431event loop::
Victor Stinnerea3183f2013-12-03 01:08:00 +01001432
1433 import asyncio
1434
Victor Stinner7f314ed2014-10-15 18:49:16 +02001435 def hello_world(loop):
Carol Willing5b7cbd62018-09-12 17:05:17 -07001436 """A callback to print 'Hello World' and stop the event loop"""
Victor Stinnerea3183f2013-12-03 01:08:00 +01001437 print('Hello World')
Victor Stinner7f314ed2014-10-15 18:49:16 +02001438 loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +01001439
1440 loop = asyncio.get_event_loop()
Victor Stinner7f314ed2014-10-15 18:49:16 +02001441
1442 # Schedule a call to hello_world()
1443 loop.call_soon(hello_world, loop)
1444
1445 # Blocking call interrupted by loop.stop()
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001446 try:
1447 loop.run_forever()
1448 finally:
1449 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +01001450
Victor Stinner3e09e322013-12-03 01:22:06 +01001451.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +01001452
Yury Selivanov3faaa882018-09-14 13:32:07 -07001453 A similar :ref:`Hello World <coroutine>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001454 example created with a coroutine and the :func:`run` function.
Victor Stinnerea3183f2013-12-03 01:08:00 +01001455
Victor Stinner8b863482014-01-27 10:07:50 +01001456
Yury Selivanov394374e2018-09-17 15:35:24 -04001457.. _asyncio_example_call_later:
Victor Stinner7f314ed2014-10-15 18:49:16 +02001458
1459Display the current date with call_later()
Victor Stinnera092a612015-01-09 15:58:41 +01001460^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner7f314ed2014-10-15 18:49:16 +02001461
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001462An example of a callback displaying the current date every second. The
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001463callback uses the :meth:`loop.call_later` method to reschedule itself
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001464after 5 seconds, and then stops the event loop::
Victor Stinner7f314ed2014-10-15 18:49:16 +02001465
1466 import asyncio
1467 import datetime
1468
1469 def display_date(end_time, loop):
1470 print(datetime.datetime.now())
1471 if (loop.time() + 1.0) < end_time:
1472 loop.call_later(1, display_date, end_time, loop)
1473 else:
1474 loop.stop()
1475
1476 loop = asyncio.get_event_loop()
1477
1478 # Schedule the first call to display_date()
1479 end_time = loop.time() + 5.0
1480 loop.call_soon(display_date, end_time, loop)
1481
1482 # Blocking call interrupted by loop.stop()
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001483 try:
1484 loop.run_forever()
1485 finally:
1486 loop.close()
Victor Stinner7f314ed2014-10-15 18:49:16 +02001487
1488.. seealso::
1489
Yury Selivanov7372c3b2018-09-14 15:11:24 -07001490 A similar :ref:`current date <asyncio_example_sleep>` example
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001491 created with a coroutine and the :func:`run` function.
Victor Stinner7f314ed2014-10-15 18:49:16 +02001492
1493
Yury Selivanov394374e2018-09-17 15:35:24 -04001494.. _asyncio_example_watch_fd:
Victor Stinner8b863482014-01-27 10:07:50 +01001495
Victor Stinner04e6df32014-10-11 16:16:27 +02001496Watch a file descriptor for read events
Victor Stinnera092a612015-01-09 15:58:41 +01001497^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +02001498
1499Wait until a file descriptor received some data using the
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001500:meth:`loop.add_reader` method and then close the event loop::
Victor Stinner04e6df32014-10-11 16:16:27 +02001501
1502 import asyncio
Victor Stinnerac577d72017-11-28 21:33:20 +01001503 from socket import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +02001504
1505 # Create a pair of connected file descriptors
Victor Stinnerccd8e342014-10-11 16:30:02 +02001506 rsock, wsock = socketpair()
Carol Willing5b7cbd62018-09-12 17:05:17 -07001507
Victor Stinner04e6df32014-10-11 16:16:27 +02001508 loop = asyncio.get_event_loop()
1509
1510 def reader():
1511 data = rsock.recv(100)
1512 print("Received:", data.decode())
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001513
Victor Stinner2cef3002014-10-23 22:38:46 +02001514 # We are done: unregister the file descriptor
Victor Stinner04e6df32014-10-11 16:16:27 +02001515 loop.remove_reader(rsock)
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001516
Victor Stinner04e6df32014-10-11 16:16:27 +02001517 # Stop the event loop
1518 loop.stop()
1519
Victor Stinner2cef3002014-10-23 22:38:46 +02001520 # Register the file descriptor for read event
Victor Stinner04e6df32014-10-11 16:16:27 +02001521 loop.add_reader(rsock, reader)
1522
1523 # Simulate the reception of data from the network
1524 loop.call_soon(wsock.send, 'abc'.encode())
1525
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001526 try:
1527 # Run the event loop
1528 loop.run_forever()
1529 finally:
Carol Willing5b7cbd62018-09-12 17:05:17 -07001530 # We are done. Close sockets and the event loop.
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001531 rsock.close()
1532 wsock.close()
1533 loop.close()
Victor Stinner04e6df32014-10-11 16:16:27 +02001534
1535.. seealso::
1536
Yury Selivanov394374e2018-09-17 15:35:24 -04001537 * A similar :ref:`example <asyncio_example_create_connection>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001538 using transports, protocols, and the
1539 :meth:`loop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +02001540
Yury Selivanov394374e2018-09-17 15:35:24 -04001541 * Another similar :ref:`example <asyncio_example_create_connection-streams>`
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001542 using the high-level :func:`asyncio.open_connection` function
1543 and streams.
Victor Stinner04e6df32014-10-11 16:16:27 +02001544
1545
Yury Selivanov394374e2018-09-17 15:35:24 -04001546.. _asyncio_example_unix_signals:
1547
Victor Stinner04e6df32014-10-11 16:16:27 +02001548Set signal handlers for SIGINT and SIGTERM
Victor Stinnera092a612015-01-09 15:58:41 +01001549^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +02001550
Elvis Pranskevichus1fa2ec42018-09-17 19:16:44 -04001551(This ``signals`` example only works on Unix.)
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001552
1553Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`
1554using the :meth:`loop.add_signal_handler` method::
Victor Stinner8b863482014-01-27 10:07:50 +01001555
1556 import asyncio
1557 import functools
1558 import os
1559 import signal
1560
1561 def ask_exit(signame):
1562 print("got signal %s: exit" % signame)
1563 loop.stop()
1564
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001565 async def main():
1566 loop = asyncio.get_running_loop()
Victor Stinner8b863482014-01-27 10:07:50 +01001567
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001568 for signame in {'SIGINT', 'SIGTERM'}:
1569 loop.add_signal_handler(
1570 getattr(signal, signame),
1571 functools.partial(ask_exit, signame))
Victor Stinner2cef3002014-10-23 22:38:46 +02001572
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001573 await asyncio.sleep(3600)
1574
1575 print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
1576 print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")
1577
1578 asyncio.run(main())