blob: ade37390c63388c7f5df06dd8fdab6735b11125e [file] [log] [blame]
R David Murray6a143812013-12-20 14:37:39 -05001.. currentmodule:: asyncio
Victor Stinnerea3183f2013-12-03 01:08:00 +01002
Victor Stinner9592edb2014-02-02 15:03:02 +01003.. _asyncio-event-loop:
Victor Stinnerea3183f2013-12-03 01:08:00 +01004
Victor Stinneraea82292014-07-08 23:42:38 +02005Base Event Loop
6===============
Victor Stinnerea3183f2013-12-03 01:08:00 +01007
lf627d2c82017-07-25 17:03:51 -06008**Source code:** :source:`Lib/asyncio/events.py`
9
Victor Stinnerea3183f2013-12-03 01:08:00 +010010The event loop is the central execution device provided by :mod:`asyncio`.
Zachary Ware5e580da2015-08-27 15:54:39 -050011It provides multiple facilities, including:
Victor Stinnerea3183f2013-12-03 01:08:00 +010012
Eli Benderskyb73c8332014-02-09 06:07:47 -080013* Registering, executing and cancelling delayed calls (timeouts).
Victor Stinnerea3183f2013-12-03 01:08:00 +010014
Victor Stinner9592edb2014-02-02 15:03:02 +010015* Creating client and server :ref:`transports <asyncio-transport>` for various
Eli Benderskyb73c8332014-02-09 06:07:47 -080016 kinds of communication.
Victor Stinnerea3183f2013-12-03 01:08:00 +010017
Eli Bendersky136fea22014-02-09 06:55:58 -080018* Launching subprocesses and the associated :ref:`transports
19 <asyncio-transport>` for communication with an external program.
Victor Stinnerea3183f2013-12-03 01:08:00 +010020
Eli Benderskyb73c8332014-02-09 06:07:47 -080021* Delegating costly function calls to a pool of threads.
Victor Stinnerea3183f2013-12-03 01:08:00 +010022
Victor Stinneraea82292014-07-08 23:42:38 +020023.. class:: BaseEventLoop
Eli Bendersky136fea22014-02-09 06:55:58 -080024
Guido van Rossumf68afd82016-08-08 09:41:21 -070025 This class is an implementation detail. It is a subclass of
26 :class:`AbstractEventLoop` and may be a base class of concrete
27 event loop implementations found in :mod:`asyncio`. It should not
28 be used directly; use :class:`AbstractEventLoop` instead.
29 ``BaseEventLoop`` should not be subclassed by third-party code; the
30 internal interface is not stable.
31
32.. class:: AbstractEventLoop
33
34 Abstract base class of event loops.
Victor Stinnerea3183f2013-12-03 01:08:00 +010035
Victor Stinner83704962015-02-25 14:24:15 +010036 This class is :ref:`not thread safe <asyncio-multithreading>`.
37
Victor Stinnerea3183f2013-12-03 01:08:00 +010038Run an event loop
39-----------------
40
Guido van Rossumf68afd82016-08-08 09:41:21 -070041.. method:: AbstractEventLoop.run_forever()
Victor Stinnerea3183f2013-12-03 01:08:00 +010042
Guido van Rossum41f69f42015-11-19 13:28:47 -080043 Run until :meth:`stop` is called. If :meth:`stop` is called before
44 :meth:`run_forever()` is called, this polls the I/O selector once
45 with a timeout of zero, runs all callbacks scheduled in response to
46 I/O events (and those that were already scheduled), and then exits.
47 If :meth:`stop` is called while :meth:`run_forever` is running,
48 this will run the current batch of callbacks and then exit. Note
49 that callbacks scheduled by callbacks will not run in that case;
50 they will run the next time :meth:`run_forever` is called.
51
Guido van Rossum82f9fea2015-11-19 13:33:34 -080052 .. versionchanged:: 3.5.1
Victor Stinnerea3183f2013-12-03 01:08:00 +010053
Guido van Rossumf68afd82016-08-08 09:41:21 -070054.. method:: AbstractEventLoop.run_until_complete(future)
Victor Stinnerea3183f2013-12-03 01:08:00 +010055
Victor Stinner99c2ab42013-12-03 19:17:25 +010056 Run until the :class:`Future` is done.
Victor Stinnerea3183f2013-12-03 01:08:00 +010057
Victor Stinner530ef2f2014-07-08 12:39:10 +020058 If the argument is a :ref:`coroutine object <coroutine>`, it is wrapped by
Yury Selivanov04356e12015-06-30 22:13:22 -040059 :func:`ensure_future`.
Victor Stinnerea3183f2013-12-03 01:08:00 +010060
61 Return the Future's result, or raise its exception.
62
Guido van Rossumf68afd82016-08-08 09:41:21 -070063.. method:: AbstractEventLoop.is_running()
Victor Stinnerea3183f2013-12-03 01:08:00 +010064
65 Returns running status of event loop.
66
Guido van Rossumf68afd82016-08-08 09:41:21 -070067.. method:: AbstractEventLoop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +010068
69 Stop running the event loop.
70
Guido van Rossum41f69f42015-11-19 13:28:47 -080071 This causes :meth:`run_forever` to exit at the next suitable
72 opportunity (see there for more details).
73
Guido van Rossum82f9fea2015-11-19 13:33:34 -080074 .. versionchanged:: 3.5.1
Victor Stinnerea3183f2013-12-03 01:08:00 +010075
Guido van Rossumf68afd82016-08-08 09:41:21 -070076.. method:: AbstractEventLoop.is_closed()
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +020077
78 Returns ``True`` if the event loop was closed.
79
80 .. versionadded:: 3.4.2
81
Guido van Rossumf68afd82016-08-08 09:41:21 -070082.. method:: AbstractEventLoop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +010083
Guido van Rossum41f69f42015-11-19 13:28:47 -080084 Close the event loop. The loop must not be running. Pending
85 callbacks will be lost.
Victor Stinnerea3183f2013-12-03 01:08:00 +010086
87 This clears the queues and shuts down the executor, but does not wait for
88 the executor to finish.
89
90 This is idempotent and irreversible. No other methods should be called after
91 this one.
92
Yury Selivanov03660042016-12-15 17:36:05 -050093
94.. coroutinemethod:: AbstractEventLoop.shutdown_asyncgens()
95
96 Schedule all currently open :term:`asynchronous generator` objects to
97 close with an :meth:`~agen.aclose()` call. After calling this method,
98 the event loop will issue a warning whenever a new asynchronous generator
99 is iterated. Should be used to finalize all scheduled asynchronous
100 generators reliably. Example::
101
102 try:
103 loop.run_forever()
104 finally:
105 loop.run_until_complete(loop.shutdown_asyncgens())
106 loop.close()
107
108 .. versionadded:: 3.6
109
110
Victor Stinner8464c242014-11-28 13:15:41 +0100111.. _asyncio-pass-keywords:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100112
113Calls
114-----
115
Victor Stinner8464c242014-11-28 13:15:41 +0100116Most :mod:`asyncio` functions don't accept keywords. If you want to pass
117keywords to your callback, use :func:`functools.partial`. For example,
118``loop.call_soon(functools.partial(print, "Hello", flush=True))`` will call
119``print("Hello", flush=True)``.
120
121.. note::
122 :func:`functools.partial` is better than ``lambda`` functions, because
123 :mod:`asyncio` can inspect :func:`functools.partial` object to display
124 parameters in debug mode, whereas ``lambda`` functions have a poor
125 representation.
126
Guido van Rossumf68afd82016-08-08 09:41:21 -0700127.. method:: AbstractEventLoop.call_soon(callback, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100128
Victor Stinner4d5115c2014-12-15 17:50:55 +0100129 Arrange for a callback to be called as soon as possible. The callback is
130 called after :meth:`call_soon` returns, when control returns to the event
131 loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100132
Serhiy Storchaka4ecfa452016-05-16 09:31:54 +0300133 This operates as a :abbr:`FIFO (first-in, first-out)` queue, callbacks
134 are called in the order in which they are registered. Each callback
135 will be called exactly once.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100136
137 Any positional arguments after the callback will be passed to the
138 callback when it is called.
139
Yury Selivanov1096f762015-06-25 13:49:52 -0400140 An instance of :class:`asyncio.Handle` is returned, which can be
141 used to cancel the callback.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500142
Victor Stinner8464c242014-11-28 13:15:41 +0100143 :ref:`Use functools.partial to pass keywords to the callback
144 <asyncio-pass-keywords>`.
145
Guido van Rossumf68afd82016-08-08 09:41:21 -0700146.. method:: AbstractEventLoop.call_soon_threadsafe(callback, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100147
148 Like :meth:`call_soon`, but thread safe.
149
Victor Stinner83704962015-02-25 14:24:15 +0100150 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
151 section of the documentation.
152
Victor Stinnerea3183f2013-12-03 01:08:00 +0100153
Victor Stinner45b27ed2014-02-01 02:36:43 +0100154.. _asyncio-delayed-calls:
155
Victor Stinnerea3183f2013-12-03 01:08:00 +0100156Delayed calls
157-------------
158
159The event loop has its own internal clock for computing timeouts.
160Which clock is used depends on the (platform-specific) event loop
161implementation; ideally it is a monotonic clock. This will generally be
162a different clock than :func:`time.time`.
163
Victor Stinnerfd9d3742014-02-18 09:37:43 +0100164.. note::
165
166 Timeouts (relative *delay* or absolute *when*) should not exceed one day.
167
Victor Stinner45b27ed2014-02-01 02:36:43 +0100168
Guido van Rossumf68afd82016-08-08 09:41:21 -0700169.. method:: AbstractEventLoop.call_later(delay, callback, *args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100170
171 Arrange for the *callback* to be called after the given *delay*
172 seconds (either an int or float).
173
Yury Selivanov1096f762015-06-25 13:49:52 -0400174 An instance of :class:`asyncio.Handle` is returned, which can be
175 used to cancel the callback.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100176
177 *callback* will be called exactly once per call to :meth:`call_later`.
178 If two callbacks are scheduled for exactly the same time, it is
179 undefined which will be called first.
180
181 The optional positional *args* will be passed to the callback when it
182 is called. If you want the callback to be called with some named
183 arguments, use a closure or :func:`functools.partial`.
184
Victor Stinner8464c242014-11-28 13:15:41 +0100185 :ref:`Use functools.partial to pass keywords to the callback
186 <asyncio-pass-keywords>`.
187
Guido van Rossumf68afd82016-08-08 09:41:21 -0700188.. method:: AbstractEventLoop.call_at(when, callback, *args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100189
190 Arrange for the *callback* to be called at the given absolute timestamp
Berker Peksagb5563992014-11-07 19:51:07 +0200191 *when* (an int or float), using the same time reference as
Guido van Rossumf68afd82016-08-08 09:41:21 -0700192 :meth:`AbstractEventLoop.time`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100193
194 This method's behavior is the same as :meth:`call_later`.
195
Yury Selivanov1096f762015-06-25 13:49:52 -0400196 An instance of :class:`asyncio.Handle` is returned, which can be
197 used to cancel the callback.
198
Victor Stinner8464c242014-11-28 13:15:41 +0100199 :ref:`Use functools.partial to pass keywords to the callback
200 <asyncio-pass-keywords>`.
201
Guido van Rossumf68afd82016-08-08 09:41:21 -0700202.. method:: AbstractEventLoop.time()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100203
204 Return the current time, as a :class:`float` value, according to the
205 event loop's internal clock.
206
Victor Stinner3e09e322013-12-03 01:22:06 +0100207.. seealso::
208
209 The :func:`asyncio.sleep` function.
210
Victor Stinnerea3183f2013-12-03 01:08:00 +0100211
Yury Selivanov950204d2016-05-16 16:23:00 -0400212Futures
213-------
214
Guido van Rossumf68afd82016-08-08 09:41:21 -0700215.. method:: AbstractEventLoop.create_future()
Yury Selivanov950204d2016-05-16 16:23:00 -0400216
217 Create an :class:`asyncio.Future` object attached to the loop.
218
219 This is a preferred way to create futures in asyncio, as event
220 loop implementations can provide alternative implementations
221 of the Future class (with better performance or instrumentation).
222
223 .. versionadded:: 3.5.2
224
225
Yury Selivanovbb961342015-06-25 11:54:34 -0400226Tasks
227-----
Victor Stinner530ef2f2014-07-08 12:39:10 +0200228
Guido van Rossumf68afd82016-08-08 09:41:21 -0700229.. method:: AbstractEventLoop.create_task(coro)
Victor Stinner530ef2f2014-07-08 12:39:10 +0200230
231 Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in
232 a future. Return a :class:`Task` object.
233
234 Third-party event loops can use their own subclass of :class:`Task` for
235 interoperability. In this case, the result type is a subclass of
236 :class:`Task`.
237
Victor Stinner337e03f2014-08-11 01:11:13 +0200238 This method was added in Python 3.4.2. Use the :func:`async` function to
239 support also older Python versions.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200240
241 .. versionadded:: 3.4.2
242
Guido van Rossumf68afd82016-08-08 09:41:21 -0700243.. method:: AbstractEventLoop.set_task_factory(factory)
Yury Selivanov71854612015-05-11 16:28:27 -0400244
245 Set a task factory that will be used by
Guido van Rossumf68afd82016-08-08 09:41:21 -0700246 :meth:`AbstractEventLoop.create_task`.
Yury Selivanov71854612015-05-11 16:28:27 -0400247
248 If *factory* is ``None`` the default task factory will be set.
249
250 If *factory* is a *callable*, it should have a signature matching
251 ``(loop, coro)``, where *loop* will be a reference to the active
252 event loop, *coro* will be a coroutine object. The callable
253 must return an :class:`asyncio.Future` compatible object.
254
255 .. versionadded:: 3.4.4
256
Guido van Rossumf68afd82016-08-08 09:41:21 -0700257.. method:: AbstractEventLoop.get_task_factory()
Yury Selivanov71854612015-05-11 16:28:27 -0400258
259 Return a task factory, or ``None`` if the default one is in use.
260
261 .. versionadded:: 3.4.4
262
Victor Stinner530ef2f2014-07-08 12:39:10 +0200263
Victor Stinnerea3183f2013-12-03 01:08:00 +0100264Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100265--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100266
Guido van Rossumf68afd82016-08-08 09:41:21 -0700267.. coroutinemethod:: AbstractEventLoop.create_connection(protocol_factory, host=None, port=None, \*, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100268
269 Create a streaming transport connection to a given Internet *host* and
Victor Stinnera6919aa2014-02-19 13:32:34 +0100270 *port*: socket family :py:data:`~socket.AF_INET` or
271 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
272 socket type :py:data:`~socket.SOCK_STREAM`. *protocol_factory* must be a
273 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100274
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500275 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100276 establish the connection in the background. When successful, the
277 coroutine returns a ``(transport, protocol)`` pair.
278
279 The chronological synopsis of the underlying operation is as follows:
280
Victor Stinner9592edb2014-02-02 15:03:02 +0100281 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100282 is created to represent it.
283
284 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100285 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100286
287 #. The protocol instance is tied to the transport, and its
288 :meth:`connection_made` method is called.
289
290 #. The coroutine returns successfully with the ``(transport, protocol)``
291 pair.
292
293 The created transport is an implementation-dependent bidirectional stream.
294
295 .. note::
296 *protocol_factory* can be any kind of callable, not necessarily
297 a class. For example, if you want to use a pre-created
298 protocol instance, you can pass ``lambda: my_protocol``.
299
Martin Panterc04fb562016-02-10 05:44:01 +0000300 Options that change how the connection is created:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100301
302 * *ssl*: if given and not false, a SSL/TLS transport is created
303 (by default a plain TCP transport is created). If *ssl* is
304 a :class:`ssl.SSLContext` object, this context is used to create
305 the transport; if *ssl* is :const:`True`, a context with some
306 unspecified default settings is used.
307
Berker Peksag9c1dba22014-09-28 00:00:58 +0300308 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100309
Victor Stinnerea3183f2013-12-03 01:08:00 +0100310 * *server_hostname*, is only for use together with *ssl*,
311 and sets or overrides the hostname that the target server's certificate
312 will be matched against. By default the value of the *host* argument
313 is used. If *host* is empty, there is no default and you must pass a
314 value for *server_hostname*. If *server_hostname* is an empty
315 string, hostname matching is disabled (which is a serious security
316 risk, allowing for man-in-the-middle-attacks).
317
318 * *family*, *proto*, *flags* are the optional address family, protocol
319 and flags to be passed through to getaddrinfo() for *host* resolution.
320 If given, these should all be integers from the corresponding
321 :mod:`socket` module constants.
322
323 * *sock*, if given, should be an existing, already connected
324 :class:`socket.socket` object to be used by the transport.
325 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
326 and *local_addr* should be specified.
327
328 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
329 to bind the socket to locally. The *local_host* and *local_port*
330 are looked up using getaddrinfo(), similarly to *host* and *port*.
331
Victor Stinner60208a12015-09-15 22:41:52 +0200332 .. versionchanged:: 3.5
333
334 On Windows with :class:`ProactorEventLoop`, SSL/TLS is now supported.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200335
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100336 .. seealso::
337
338 The :func:`open_connection` function can be used to get a pair of
339 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
340
Victor Stinnerea3183f2013-12-03 01:08:00 +0100341
Guido van Rossumf68afd82016-08-08 09:41:21 -0700342.. coroutinemethod:: AbstractEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0, reuse_address=None, reuse_port=None, allow_broadcast=None, sock=None)
Victor Stinnera6919aa2014-02-19 13:32:34 +0100343
344 Create datagram connection: socket family :py:data:`~socket.AF_INET` or
345 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700346 socket type :py:data:`~socket.SOCK_DGRAM`. *protocol_factory* must be a
347 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100348
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500349 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100350 establish the connection in the background. When successful, the
351 coroutine returns a ``(transport, protocol)`` pair.
352
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700353 Options changing how the connection is created:
354
355 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
356 to bind the socket to locally. The *local_host* and *local_port*
357 are looked up using :meth:`getaddrinfo`.
358
359 * *remote_addr*, if given, is a ``(remote_host, remote_port)`` tuple used
360 to connect the socket to a remote address. The *remote_host* and
361 *remote_port* are looked up using :meth:`getaddrinfo`.
362
363 * *family*, *proto*, *flags* are the optional address family, protocol
364 and flags to be passed through to :meth:`getaddrinfo` for *host*
365 resolution. If given, these should all be integers from the
366 corresponding :mod:`socket` module constants.
367
368 * *reuse_address* tells the kernel to reuse a local socket in
369 TIME_WAIT state, without waiting for its natural timeout to
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300370 expire. If not specified will automatically be set to ``True`` on
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700371 UNIX.
372
373 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
374 same port as other existing endpoints are bound to, so long as they all
375 set this flag when being created. This option is not supported on Windows
376 and some UNIX's. If the :py:data:`~socket.SO_REUSEPORT` constant is not
377 defined then this capability is unsupported.
378
379 * *allow_broadcast* tells the kernel to allow this endpoint to send
380 messages to the broadcast address.
381
382 * *sock* can optionally be specified in order to use a preexisting,
383 already connected, :class:`socket.socket` object to be used by the
384 transport. If specified, *local_addr* and *remote_addr* should be omitted
385 (must be :const:`None`).
Victor Stinnera6919aa2014-02-19 13:32:34 +0100386
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200387 On Windows with :class:`ProactorEventLoop`, this method is not supported.
388
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200389 See :ref:`UDP echo client protocol <asyncio-udp-echo-client-protocol>` and
390 :ref:`UDP echo server protocol <asyncio-udp-echo-server-protocol>` examples.
391
Victor Stinnera6919aa2014-02-19 13:32:34 +0100392
Guido van Rossumf68afd82016-08-08 09:41:21 -0700393.. coroutinemethod:: AbstractEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
Victor Stinnera6919aa2014-02-19 13:32:34 +0100394
395 Create UNIX connection: socket family :py:data:`~socket.AF_UNIX`, socket
396 type :py:data:`~socket.SOCK_STREAM`. The :py:data:`~socket.AF_UNIX` socket
397 family is used to communicate between processes on the same machine
398 efficiently.
399
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500400 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100401 establish the connection in the background. When successful, the
402 coroutine returns a ``(transport, protocol)`` pair.
403
Guido van Rossum9e80eeb2016-11-03 14:17:25 -0700404 *path* is the name of a UNIX domain socket, and is required unless a *sock*
405 parameter is specified. Abstract UNIX sockets, :class:`str`, and
406 :class:`bytes` paths are supported.
407
Guido van Rossumf68afd82016-08-08 09:41:21 -0700408 See the :meth:`AbstractEventLoop.create_connection` method for parameters.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100409
410 Availability: UNIX.
411
412
Victor Stinnerea3183f2013-12-03 01:08:00 +0100413Creating listening connections
414------------------------------
415
Guido van Rossumf68afd82016-08-08 09:41:21 -0700416.. coroutinemethod:: AbstractEventLoop.create_server(protocol_factory, host=None, port=None, \*, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100417
Victor Stinner33f6abe2014-10-12 20:36:04 +0200418 Create a TCP server (socket type :data:`~socket.SOCK_STREAM`) bound to
419 *host* and *port*.
420
421 Return a :class:`Server` object, its :attr:`~Server.sockets` attribute
422 contains created sockets. Use the :meth:`Server.close` method to stop the
423 server: close listening sockets.
424
425 Parameters:
426
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200427 * The *host* parameter can be a string, in that case the TCP server is
428 bound to *host* and *port*. The *host* parameter can also be a sequence
429 of strings and in that case the TCP server is bound to all hosts of the
430 sequence. If *host* is an empty string or ``None``, all interfaces are
431 assumed and a list of multiple sockets will be returned (most likely one
432 for IPv4 and another one for IPv6).
Victor Stinner33f6abe2014-10-12 20:36:04 +0200433
434 * *family* can be set to either :data:`socket.AF_INET` or
435 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
436 it will be determined from host (defaults to :data:`socket.AF_UNSPEC`).
437
438 * *flags* is a bitmask for :meth:`getaddrinfo`.
439
440 * *sock* can optionally be specified in order to use a preexisting
441 socket object. If specified, *host* and *port* should be omitted (must be
442 :const:`None`).
443
444 * *backlog* is the maximum number of queued connections passed to
445 :meth:`~socket.socket.listen` (defaults to 100).
446
447 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the
448 accepted connections.
449
450 * *reuse_address* tells the kernel to reuse a local socket in
451 TIME_WAIT state, without waiting for its natural timeout to
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300452 expire. If not specified will automatically be set to ``True`` on
Victor Stinner33f6abe2014-10-12 20:36:04 +0200453 UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100454
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700455 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
456 same port as other existing endpoints are bound to, so long as they all
457 set this flag when being created. This option is not supported on
458 Windows.
459
Victor Stinnerd1432092014-06-19 17:11:49 +0200460 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100461
Victor Stinner60208a12015-09-15 22:41:52 +0200462 .. versionchanged:: 3.5
463
464 On Windows with :class:`ProactorEventLoop`, SSL/TLS is now supported.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200465
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100466 .. seealso::
467
468 The function :func:`start_server` creates a (:class:`StreamReader`,
469 :class:`StreamWriter`) pair and calls back a function with this pair.
470
Victor Stinner7b58a2b2015-09-21 18:41:05 +0200471 .. versionchanged:: 3.5.1
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200472
473 The *host* parameter can now be a sequence of strings.
474
Victor Stinnerea3183f2013-12-03 01:08:00 +0100475
Guido van Rossumf68afd82016-08-08 09:41:21 -0700476.. coroutinemethod:: AbstractEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100477
Guido van Rossumf68afd82016-08-08 09:41:21 -0700478 Similar to :meth:`AbstractEventLoop.create_server`, but specific to the
Victor Stinnera6919aa2014-02-19 13:32:34 +0100479 socket family :py:data:`~socket.AF_UNIX`.
480
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100481 This method is a :ref:`coroutine <coroutine>`.
482
Victor Stinnera6919aa2014-02-19 13:32:34 +0100483 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100484
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500485.. coroutinemethod:: BaseEventLoop.connect_accepted_socket(protocol_factory, sock, \*, ssl=None)
486
487 Handle an accepted connection.
488
489 This is used by servers that accept connections outside of
490 asyncio but that use asyncio to handle them.
491
492 Parameters:
493
494 * *sock* is a preexisting socket object returned from an ``accept``
495 call.
496
497 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the
498 accepted connections.
499
500 This method is a :ref:`coroutine <coroutine>`. When completed, the
501 coroutine returns a ``(transport, protocol)`` pair.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100502
Victor Stinnerc1567df2014-02-08 23:22:58 +0100503Watch file descriptors
504----------------------
505
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200506On Windows with :class:`SelectorEventLoop`, only socket handles are supported
507(ex: pipe file descriptors are not supported).
508
509On Windows with :class:`ProactorEventLoop`, these methods are not supported.
510
Guido van Rossumf68afd82016-08-08 09:41:21 -0700511.. method:: AbstractEventLoop.add_reader(fd, callback, \*args)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100512
513 Start watching the file descriptor for read availability and then call the
514 *callback* with specified arguments.
515
Victor Stinner8464c242014-11-28 13:15:41 +0100516 :ref:`Use functools.partial to pass keywords to the callback
517 <asyncio-pass-keywords>`.
518
Guido van Rossumf68afd82016-08-08 09:41:21 -0700519.. method:: AbstractEventLoop.remove_reader(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100520
521 Stop watching the file descriptor for read availability.
522
Guido van Rossumf68afd82016-08-08 09:41:21 -0700523.. method:: AbstractEventLoop.add_writer(fd, callback, \*args)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100524
525 Start watching the file descriptor for write availability and then call the
526 *callback* with specified arguments.
527
Victor Stinner8464c242014-11-28 13:15:41 +0100528 :ref:`Use functools.partial to pass keywords to the callback
529 <asyncio-pass-keywords>`.
530
Guido van Rossumf68afd82016-08-08 09:41:21 -0700531.. method:: AbstractEventLoop.remove_writer(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100532
533 Stop watching the file descriptor for write availability.
534
Victor Stinner04e6df32014-10-11 16:16:27 +0200535The :ref:`watch a file descriptor for read events <asyncio-watch-read-event>`
Guido van Rossumf68afd82016-08-08 09:41:21 -0700536example uses the low-level :meth:`AbstractEventLoop.add_reader` method to register
Victor Stinner04e6df32014-10-11 16:16:27 +0200537the file descriptor of a socket.
538
Victor Stinnerc1567df2014-02-08 23:22:58 +0100539
540Low-level socket operations
541---------------------------
542
Guido van Rossumf68afd82016-08-08 09:41:21 -0700543.. coroutinemethod:: AbstractEventLoop.sock_recv(sock, nbytes)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100544
Yury Selivanov55c50842016-06-08 12:48:15 -0400545 Receive data from the socket. Modeled after blocking
546 :meth:`socket.socket.recv` method.
547
548 The return value is a bytes object
Victor Stinnerc1567df2014-02-08 23:22:58 +0100549 representing the data received. The maximum amount of data to be received
550 at once is specified by *nbytes*.
551
Victor Stinnerd84fd732014-08-26 01:01:59 +0200552 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
553 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200554
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500555 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100556
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200557.. coroutinemethod:: AbstractEventLoop.sock_recv_into(sock, buf)
558
559 Receive data from the socket. Modeled after blocking
560 :meth:`socket.socket.recv_into` method.
561
562 The received data is written into *buf* (a writable buffer).
563 The return value is the number of bytes written.
564
565 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
566 non-blocking.
567
568 This method is a :ref:`coroutine <coroutine>`.
569
570 .. versionadded:: 3.7
571
Guido van Rossumf68afd82016-08-08 09:41:21 -0700572.. coroutinemethod:: AbstractEventLoop.sock_sendall(sock, data)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100573
Yury Selivanov55c50842016-06-08 12:48:15 -0400574 Send data to the socket. Modeled after blocking
575 :meth:`socket.socket.sendall` method.
576
577 The socket must be connected to a remote socket.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100578 This method continues to send data from *data* until either all data has
579 been sent or an error occurs. ``None`` is returned on success. On error,
580 an exception is raised, and there is no way to determine how much data, if
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500581 any, was successfully processed by the receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100582
Victor Stinnerd84fd732014-08-26 01:01:59 +0200583 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
584 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200585
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500586 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100587
Guido van Rossumf68afd82016-08-08 09:41:21 -0700588.. coroutinemethod:: AbstractEventLoop.sock_connect(sock, address)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100589
Yury Selivanov55c50842016-06-08 12:48:15 -0400590 Connect to a remote socket at *address*. Modeled after
591 blocking :meth:`socket.socket.connect` method.
Victor Stinner1b0580b2014-02-13 09:24:37 +0100592
Victor Stinnerd84fd732014-08-26 01:01:59 +0200593 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
594 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200595
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500596 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100597
Yury Selivanov55c50842016-06-08 12:48:15 -0400598 .. versionchanged:: 3.5.2
599 ``address`` no longer needs to be resolved. ``sock_connect``
600 will try to check if the *address* is already resolved by calling
601 :func:`socket.inet_pton`. If not,
Guido van Rossumf68afd82016-08-08 09:41:21 -0700602 :meth:`AbstractEventLoop.getaddrinfo` will be used to resolve the
Yury Selivanov55c50842016-06-08 12:48:15 -0400603 *address*.
604
Victor Stinnerc1567df2014-02-08 23:22:58 +0100605 .. seealso::
606
Guido van Rossumf68afd82016-08-08 09:41:21 -0700607 :meth:`AbstractEventLoop.create_connection`
Yury Selivanov55c50842016-06-08 12:48:15 -0400608 and :func:`asyncio.open_connection() <open_connection>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100609
610
Guido van Rossumf68afd82016-08-08 09:41:21 -0700611.. coroutinemethod:: AbstractEventLoop.sock_accept(sock)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100612
Yury Selivanov55c50842016-06-08 12:48:15 -0400613 Accept a connection. Modeled after blocking
614 :meth:`socket.socket.accept`.
615
616 The socket must be bound to an address and listening
Victor Stinnerc1567df2014-02-08 23:22:58 +0100617 for connections. The return value is a pair ``(conn, address)`` where *conn*
618 is a *new* socket object usable to send and receive data on the connection,
619 and *address* is the address bound to the socket on the other end of the
620 connection.
621
Victor Stinnerec2ce092014-07-29 23:12:22 +0200622 The socket *sock* must be non-blocking.
623
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500624 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100625
626 .. seealso::
627
Guido van Rossumf68afd82016-08-08 09:41:21 -0700628 :meth:`AbstractEventLoop.create_server` and :func:`start_server`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100629
630
631Resolve host name
632-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100633
Guido van Rossumf68afd82016-08-08 09:41:21 -0700634.. coroutinemethod:: AbstractEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100635
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500636 This method is a :ref:`coroutine <coroutine>`, similar to
637 :meth:`socket.getaddrinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100638
Guido van Rossumf68afd82016-08-08 09:41:21 -0700639.. coroutinemethod:: AbstractEventLoop.getnameinfo(sockaddr, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100640
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500641 This method is a :ref:`coroutine <coroutine>`, similar to
642 :meth:`socket.getnameinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100643
644
Victor Stinner984600f2014-03-25 09:40:26 +0100645Connect pipes
646-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100647
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200648On Windows with :class:`SelectorEventLoop`, these methods are not supported.
649Use :class:`ProactorEventLoop` to support pipes on Windows.
650
Guido van Rossumf68afd82016-08-08 09:41:21 -0700651.. coroutinemethod:: AbstractEventLoop.connect_read_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100652
Victor Stinnerd84fd732014-08-26 01:01:59 +0200653 Register read pipe in eventloop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100654
655 *protocol_factory* should instantiate object with :class:`Protocol`
Victor Stinnera5b257a2014-05-29 00:14:03 +0200656 interface. *pipe* is a :term:`file-like object <file object>`.
657 Return pair ``(transport, protocol)``, where *transport* supports the
Victor Stinnerea3183f2013-12-03 01:08:00 +0100658 :class:`ReadTransport` interface.
659
Victor Stinnerd84fd732014-08-26 01:01:59 +0200660 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
661 non-blocking mode.
662
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500663 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100664
Guido van Rossumf68afd82016-08-08 09:41:21 -0700665.. coroutinemethod:: AbstractEventLoop.connect_write_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100666
667 Register write pipe in eventloop.
668
669 *protocol_factory* should instantiate object with :class:`BaseProtocol`
Victor Stinner2cef3002014-10-23 22:38:46 +0200670 interface. *pipe* is :term:`file-like object <file object>`.
671 Return pair ``(transport, protocol)``, where *transport* supports
Victor Stinnerea3183f2013-12-03 01:08:00 +0100672 :class:`WriteTransport` interface.
673
Victor Stinnerd84fd732014-08-26 01:01:59 +0200674 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
675 non-blocking mode.
676
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500677 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100678
Victor Stinner08444382014-02-02 22:43:39 +0100679.. seealso::
680
Guido van Rossumf68afd82016-08-08 09:41:21 -0700681 The :meth:`AbstractEventLoop.subprocess_exec` and
682 :meth:`AbstractEventLoop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100683
Victor Stinnerea3183f2013-12-03 01:08:00 +0100684
Victor Stinner8b863482014-01-27 10:07:50 +0100685UNIX signals
686------------
687
688Availability: UNIX only.
689
Guido van Rossumf68afd82016-08-08 09:41:21 -0700690.. method:: AbstractEventLoop.add_signal_handler(signum, callback, \*args)
Victor Stinner8b863482014-01-27 10:07:50 +0100691
692 Add a handler for a signal.
693
694 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
695 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
696
Victor Stinner8464c242014-11-28 13:15:41 +0100697 :ref:`Use functools.partial to pass keywords to the callback
698 <asyncio-pass-keywords>`.
699
Guido van Rossumf68afd82016-08-08 09:41:21 -0700700.. method:: AbstractEventLoop.remove_signal_handler(sig)
Victor Stinner8b863482014-01-27 10:07:50 +0100701
702 Remove a handler for a signal.
703
704 Return ``True`` if a signal handler was removed, ``False`` if not.
705
706.. seealso::
707
708 The :mod:`signal` module.
709
710
Victor Stinnerea3183f2013-12-03 01:08:00 +0100711Executor
712--------
713
714Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
715pool of processes). By default, an event loop uses a thread pool executor
716(:class:`~concurrent.futures.ThreadPoolExecutor`).
717
Guido van Rossumf68afd82016-08-08 09:41:21 -0700718.. coroutinemethod:: AbstractEventLoop.run_in_executor(executor, func, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100719
Andrew Svetlov1c62b522015-10-01 09:48:08 +0300720 Arrange for a *func* to be called in the specified executor.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100721
Larry Hastings3732ed22014-03-15 21:13:56 -0700722 The *executor* argument should be an :class:`~concurrent.futures.Executor`
723 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100724
Andrew Svetlov1c62b522015-10-01 09:48:08 +0300725 :ref:`Use functools.partial to pass keywords to the *func*
Victor Stinner8464c242014-11-28 13:15:41 +0100726 <asyncio-pass-keywords>`.
727
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500728 This method is a :ref:`coroutine <coroutine>`.
729
Yury Selivanove8a60452016-10-21 17:40:42 -0400730 .. versionchanged:: 3.5.3
731 :meth:`BaseEventLoop.run_in_executor` no longer configures the
732 ``max_workers`` of the thread pool executor it creates, instead
733 leaving it up to the thread pool executor
734 (:class:`~concurrent.futures.ThreadPoolExecutor`) to set the
735 default.
736
Guido van Rossumf68afd82016-08-08 09:41:21 -0700737.. method:: AbstractEventLoop.set_default_executor(executor)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100738
739 Set the default executor used by :meth:`run_in_executor`.
740
741
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500742Error Handling API
743------------------
744
Martin Panterc04fb562016-02-10 05:44:01 +0000745Allows customizing how exceptions are handled in the event loop.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500746
Guido van Rossumf68afd82016-08-08 09:41:21 -0700747.. method:: AbstractEventLoop.set_exception_handler(handler)
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500748
749 Set *handler* as the new event loop exception handler.
750
751 If *handler* is ``None``, the default exception handler will
752 be set.
753
754 If *handler* is a callable object, it should have a
755 matching signature to ``(loop, context)``, where ``loop``
756 will be a reference to the active event loop, ``context``
757 will be a ``dict`` object (see :meth:`call_exception_handler`
758 documentation for details about context).
759
Guido van Rossumf68afd82016-08-08 09:41:21 -0700760.. method:: AbstractEventLoop.get_exception_handler()
Yury Selivanov950204d2016-05-16 16:23:00 -0400761
762 Return the exception handler, or ``None`` if the default one
763 is in use.
764
765 .. versionadded:: 3.5.2
766
Guido van Rossumf68afd82016-08-08 09:41:21 -0700767.. method:: AbstractEventLoop.default_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500768
769 Default exception handler.
770
771 This is called when an exception occurs and no exception
772 handler is set, and can be called by a custom exception
773 handler that wants to defer to the default behavior.
774
775 *context* parameter has the same meaning as in
776 :meth:`call_exception_handler`.
777
Guido van Rossumf68afd82016-08-08 09:41:21 -0700778.. method:: AbstractEventLoop.call_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500779
780 Call the current event loop exception handler.
781
782 *context* is a ``dict`` object containing the following keys
783 (new keys may be introduced later):
784
785 * 'message': Error message;
786 * 'exception' (optional): Exception object;
787 * 'future' (optional): :class:`asyncio.Future` instance;
788 * 'handle' (optional): :class:`asyncio.Handle` instance;
789 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
790 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
791 * 'socket' (optional): :class:`socket.socket` instance.
792
793 .. note::
794
795 Note: this method should not be overloaded in subclassed
796 event loops. For any custom exception handling, use
797 :meth:`set_exception_handler()` method.
798
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100799Debug mode
800----------
801
Guido van Rossumf68afd82016-08-08 09:41:21 -0700802.. method:: AbstractEventLoop.get_debug()
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100803
Victor Stinner7b7120e2014-06-23 00:12:14 +0200804 Get the debug mode (:class:`bool`) of the event loop.
805
806 The default value is ``True`` if the environment variable
807 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
808 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100809
Victor Stinner64d750b2014-06-18 03:25:23 +0200810 .. versionadded:: 3.4.2
811
Guido van Rossumf68afd82016-08-08 09:41:21 -0700812.. method:: AbstractEventLoop.set_debug(enabled: bool)
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100813
814 Set the debug mode of the event loop.
815
Victor Stinner64d750b2014-06-18 03:25:23 +0200816 .. versionadded:: 3.4.2
817
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100818.. seealso::
819
Victor Stinner62511fd2014-06-23 00:36:11 +0200820 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100821
Victor Stinner8c462c52014-01-24 18:11:43 +0100822Server
823------
824
Victor Stinner8ebeb032014-07-11 23:47:40 +0200825.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +0100826
Victor Stinner8ebeb032014-07-11 23:47:40 +0200827 Server listening on sockets.
828
Guido van Rossumf68afd82016-08-08 09:41:21 -0700829 Object created by the :meth:`AbstractEventLoop.create_server` method and the
R David Murray756f0b12015-01-29 19:53:33 -0500830 :func:`start_server` function. Don't instantiate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +0100831
832 .. method:: close()
833
Victor Stinner4bfb14a2014-07-12 03:20:24 +0200834 Stop serving: close listening sockets and set the :attr:`sockets`
835 attribute to ``None``.
836
Berker Peksag49c9edf2016-01-20 07:14:22 +0200837 The sockets that represent existing incoming client connections are left
838 open.
Victor Stinner8ebeb032014-07-11 23:47:40 +0200839
Berker Peksag49c9edf2016-01-20 07:14:22 +0200840 The server is closed asynchronously, use the :meth:`wait_closed`
841 coroutine to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100842
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100843 .. coroutinemethod:: wait_closed()
Victor Stinner8c462c52014-01-24 18:11:43 +0100844
Victor Stinner8ebeb032014-07-11 23:47:40 +0200845 Wait until the :meth:`close` method completes.
846
847 This method is a :ref:`coroutine <coroutine>`.
848
849 .. attribute:: sockets
850
851 List of :class:`socket.socket` objects the server is listening to, or
852 ``None`` if the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100853
854
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500855Handle
856------
857
858.. class:: Handle
859
Guido van Rossumf68afd82016-08-08 09:41:21 -0700860 A callback wrapper object returned by :func:`AbstractEventLoop.call_soon`,
861 :func:`AbstractEventLoop.call_soon_threadsafe`, :func:`AbstractEventLoop.call_later`,
862 and :func:`AbstractEventLoop.call_at`.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500863
864 .. method:: cancel()
865
Yury Selivanov1096f762015-06-25 13:49:52 -0400866 Cancel the call. If the callback is already canceled or executed,
867 this method has no effect.
Victor Stinneraea82292014-07-08 23:42:38 +0200868
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500869
Victor Stinner6888b962014-10-11 16:15:58 +0200870Event loop examples
Victor Stinnera092a612015-01-09 15:58:41 +0100871-------------------
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500872
Victor Stinner3e09e322013-12-03 01:22:06 +0100873.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100874
Victor Stinner7f314ed2014-10-15 18:49:16 +0200875Hello World with call_soon()
Victor Stinnera092a612015-01-09 15:58:41 +0100876^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100877
Guido van Rossumf68afd82016-08-08 09:41:21 -0700878Example using the :meth:`AbstractEventLoop.call_soon` method to schedule a
Victor Stinner7f314ed2014-10-15 18:49:16 +0200879callback. The callback displays ``"Hello World"`` and then stops the event
880loop::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100881
882 import asyncio
883
Victor Stinner7f314ed2014-10-15 18:49:16 +0200884 def hello_world(loop):
Victor Stinnerea3183f2013-12-03 01:08:00 +0100885 print('Hello World')
Victor Stinner7f314ed2014-10-15 18:49:16 +0200886 loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100887
888 loop = asyncio.get_event_loop()
Victor Stinner7f314ed2014-10-15 18:49:16 +0200889
890 # Schedule a call to hello_world()
891 loop.call_soon(hello_world, loop)
892
893 # Blocking call interrupted by loop.stop()
894 loop.run_forever()
895 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100896
Victor Stinner3e09e322013-12-03 01:22:06 +0100897.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100898
Victor Stinner6888b962014-10-11 16:15:58 +0200899 The :ref:`Hello World coroutine <asyncio-hello-world-coroutine>` example
900 uses a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100901
Victor Stinner8b863482014-01-27 10:07:50 +0100902
Victor Stinner7f314ed2014-10-15 18:49:16 +0200903.. _asyncio-date-callback:
904
905Display the current date with call_later()
Victor Stinnera092a612015-01-09 15:58:41 +0100906^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner7f314ed2014-10-15 18:49:16 +0200907
908Example of callback displaying the current date every second. The callback uses
Guido van Rossumf68afd82016-08-08 09:41:21 -0700909the :meth:`AbstractEventLoop.call_later` method to reschedule itself during 5
Victor Stinner7f314ed2014-10-15 18:49:16 +0200910seconds, and then stops the event loop::
911
912 import asyncio
913 import datetime
914
915 def display_date(end_time, loop):
916 print(datetime.datetime.now())
917 if (loop.time() + 1.0) < end_time:
918 loop.call_later(1, display_date, end_time, loop)
919 else:
920 loop.stop()
921
922 loop = asyncio.get_event_loop()
923
924 # Schedule the first call to display_date()
925 end_time = loop.time() + 5.0
926 loop.call_soon(display_date, end_time, loop)
927
928 # Blocking call interrupted by loop.stop()
929 loop.run_forever()
930 loop.close()
931
932.. seealso::
933
934 The :ref:`coroutine displaying the current date
935 <asyncio-date-coroutine>` example uses a :ref:`coroutine
936 <coroutine>`.
937
938
Victor Stinner04e6df32014-10-11 16:16:27 +0200939.. _asyncio-watch-read-event:
Victor Stinner8b863482014-01-27 10:07:50 +0100940
Victor Stinner04e6df32014-10-11 16:16:27 +0200941Watch a file descriptor for read events
Victor Stinnera092a612015-01-09 15:58:41 +0100942^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +0200943
944Wait until a file descriptor received some data using the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700945:meth:`AbstractEventLoop.add_reader` method and then close the event loop::
Victor Stinner04e6df32014-10-11 16:16:27 +0200946
947 import asyncio
Victor Stinnerccd8e342014-10-11 16:30:02 +0200948 try:
949 from socket import socketpair
950 except ImportError:
951 from asyncio.windows_utils import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +0200952
953 # Create a pair of connected file descriptors
Victor Stinnerccd8e342014-10-11 16:30:02 +0200954 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200955 loop = asyncio.get_event_loop()
956
957 def reader():
958 data = rsock.recv(100)
959 print("Received:", data.decode())
Victor Stinner2cef3002014-10-23 22:38:46 +0200960 # We are done: unregister the file descriptor
Victor Stinner04e6df32014-10-11 16:16:27 +0200961 loop.remove_reader(rsock)
962 # Stop the event loop
963 loop.stop()
964
Victor Stinner2cef3002014-10-23 22:38:46 +0200965 # Register the file descriptor for read event
Victor Stinner04e6df32014-10-11 16:16:27 +0200966 loop.add_reader(rsock, reader)
967
968 # Simulate the reception of data from the network
969 loop.call_soon(wsock.send, 'abc'.encode())
970
971 # Run the event loop
972 loop.run_forever()
973
974 # We are done, close sockets and the event loop
975 rsock.close()
976 wsock.close()
977 loop.close()
978
979.. seealso::
980
981 The :ref:`register an open socket to wait for data using a protocol
982 <asyncio-register-socket>` example uses a low-level protocol created by the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700983 :meth:`AbstractEventLoop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200984
985 The :ref:`register an open socket to wait for data using streams
986 <asyncio-register-socket-streams>` example uses high-level streams
987 created by the :func:`open_connection` function in a coroutine.
988
989
990Set signal handlers for SIGINT and SIGTERM
Victor Stinnera092a612015-01-09 15:58:41 +0100991^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +0200992
993Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM` using
Guido van Rossumf68afd82016-08-08 09:41:21 -0700994the :meth:`AbstractEventLoop.add_signal_handler` method::
Victor Stinner8b863482014-01-27 10:07:50 +0100995
996 import asyncio
997 import functools
998 import os
999 import signal
1000
1001 def ask_exit(signame):
1002 print("got signal %s: exit" % signame)
1003 loop.stop()
1004
1005 loop = asyncio.get_event_loop()
1006 for signame in ('SIGINT', 'SIGTERM'):
1007 loop.add_signal_handler(getattr(signal, signame),
1008 functools.partial(ask_exit, signame))
1009
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +03001010 print("Event loop running forever, press Ctrl+C to interrupt.")
Victor Stinner8b863482014-01-27 10:07:50 +01001011 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
Victor Stinner63b21a82014-07-05 15:38:59 +02001012 try:
1013 loop.run_forever()
1014 finally:
1015 loop.close()
Victor Stinner2cef3002014-10-23 22:38:46 +02001016
1017This example only works on UNIX.