blob: bb602c663e91e25cf1b9d9c1aee9bbb42a08cee9 [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
8The event loop is the central execution device provided by :mod:`asyncio`.
Zachary Ware5e580da2015-08-27 15:54:39 -05009It provides multiple facilities, including:
Victor Stinnerea3183f2013-12-03 01:08:00 +010010
Eli Benderskyb73c8332014-02-09 06:07:47 -080011* Registering, executing and cancelling delayed calls (timeouts).
Victor Stinnerea3183f2013-12-03 01:08:00 +010012
Victor Stinner9592edb2014-02-02 15:03:02 +010013* Creating client and server :ref:`transports <asyncio-transport>` for various
Eli Benderskyb73c8332014-02-09 06:07:47 -080014 kinds of communication.
Victor Stinnerea3183f2013-12-03 01:08:00 +010015
Eli Bendersky136fea22014-02-09 06:55:58 -080016* Launching subprocesses and the associated :ref:`transports
17 <asyncio-transport>` for communication with an external program.
Victor Stinnerea3183f2013-12-03 01:08:00 +010018
Eli Benderskyb73c8332014-02-09 06:07:47 -080019* Delegating costly function calls to a pool of threads.
Victor Stinnerea3183f2013-12-03 01:08:00 +010020
Victor Stinneraea82292014-07-08 23:42:38 +020021.. class:: BaseEventLoop
Eli Bendersky136fea22014-02-09 06:55:58 -080022
Guido van Rossumf68afd82016-08-08 09:41:21 -070023 This class is an implementation detail. It is a subclass of
24 :class:`AbstractEventLoop` and may be a base class of concrete
25 event loop implementations found in :mod:`asyncio`. It should not
26 be used directly; use :class:`AbstractEventLoop` instead.
27 ``BaseEventLoop`` should not be subclassed by third-party code; the
28 internal interface is not stable.
29
30.. class:: AbstractEventLoop
31
32 Abstract base class of event loops.
Victor Stinnerea3183f2013-12-03 01:08:00 +010033
Victor Stinner83704962015-02-25 14:24:15 +010034 This class is :ref:`not thread safe <asyncio-multithreading>`.
35
Victor Stinnerea3183f2013-12-03 01:08:00 +010036Run an event loop
37-----------------
38
Guido van Rossumf68afd82016-08-08 09:41:21 -070039.. method:: AbstractEventLoop.run_forever()
Victor Stinnerea3183f2013-12-03 01:08:00 +010040
Guido van Rossum41f69f42015-11-19 13:28:47 -080041 Run until :meth:`stop` is called. If :meth:`stop` is called before
42 :meth:`run_forever()` is called, this polls the I/O selector once
43 with a timeout of zero, runs all callbacks scheduled in response to
44 I/O events (and those that were already scheduled), and then exits.
45 If :meth:`stop` is called while :meth:`run_forever` is running,
46 this will run the current batch of callbacks and then exit. Note
47 that callbacks scheduled by callbacks will not run in that case;
48 they will run the next time :meth:`run_forever` is called.
49
Guido van Rossum82f9fea2015-11-19 13:33:34 -080050 .. versionchanged:: 3.5.1
Victor Stinnerea3183f2013-12-03 01:08:00 +010051
Guido van Rossumf68afd82016-08-08 09:41:21 -070052.. method:: AbstractEventLoop.run_until_complete(future)
Victor Stinnerea3183f2013-12-03 01:08:00 +010053
Victor Stinner99c2ab42013-12-03 19:17:25 +010054 Run until the :class:`Future` is done.
Victor Stinnerea3183f2013-12-03 01:08:00 +010055
Victor Stinner530ef2f2014-07-08 12:39:10 +020056 If the argument is a :ref:`coroutine object <coroutine>`, it is wrapped by
Yury Selivanov04356e12015-06-30 22:13:22 -040057 :func:`ensure_future`.
Victor Stinnerea3183f2013-12-03 01:08:00 +010058
59 Return the Future's result, or raise its exception.
60
Guido van Rossumf68afd82016-08-08 09:41:21 -070061.. method:: AbstractEventLoop.is_running()
Victor Stinnerea3183f2013-12-03 01:08:00 +010062
63 Returns running status of event loop.
64
Guido van Rossumf68afd82016-08-08 09:41:21 -070065.. method:: AbstractEventLoop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +010066
67 Stop running the event loop.
68
Guido van Rossum41f69f42015-11-19 13:28:47 -080069 This causes :meth:`run_forever` to exit at the next suitable
70 opportunity (see there for more details).
71
Guido van Rossum82f9fea2015-11-19 13:33:34 -080072 .. versionchanged:: 3.5.1
Victor Stinnerea3183f2013-12-03 01:08:00 +010073
Guido van Rossumf68afd82016-08-08 09:41:21 -070074.. method:: AbstractEventLoop.is_closed()
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +020075
76 Returns ``True`` if the event loop was closed.
77
78 .. versionadded:: 3.4.2
79
Guido van Rossumf68afd82016-08-08 09:41:21 -070080.. method:: AbstractEventLoop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +010081
Guido van Rossum41f69f42015-11-19 13:28:47 -080082 Close the event loop. The loop must not be running. Pending
83 callbacks will be lost.
Victor Stinnerea3183f2013-12-03 01:08:00 +010084
85 This clears the queues and shuts down the executor, but does not wait for
86 the executor to finish.
87
88 This is idempotent and irreversible. No other methods should be called after
89 this one.
90
Victor Stinner8464c242014-11-28 13:15:41 +010091.. _asyncio-pass-keywords:
Victor Stinnerea3183f2013-12-03 01:08:00 +010092
93Calls
94-----
95
Victor Stinner8464c242014-11-28 13:15:41 +010096Most :mod:`asyncio` functions don't accept keywords. If you want to pass
97keywords to your callback, use :func:`functools.partial`. For example,
98``loop.call_soon(functools.partial(print, "Hello", flush=True))`` will call
99``print("Hello", flush=True)``.
100
101.. note::
102 :func:`functools.partial` is better than ``lambda`` functions, because
103 :mod:`asyncio` can inspect :func:`functools.partial` object to display
104 parameters in debug mode, whereas ``lambda`` functions have a poor
105 representation.
106
Guido van Rossumf68afd82016-08-08 09:41:21 -0700107.. method:: AbstractEventLoop.call_soon(callback, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100108
Victor Stinner4d5115c2014-12-15 17:50:55 +0100109 Arrange for a callback to be called as soon as possible. The callback is
110 called after :meth:`call_soon` returns, when control returns to the event
111 loop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100112
Serhiy Storchaka4ecfa452016-05-16 09:31:54 +0300113 This operates as a :abbr:`FIFO (first-in, first-out)` queue, callbacks
114 are called in the order in which they are registered. Each callback
115 will be called exactly once.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100116
117 Any positional arguments after the callback will be passed to the
118 callback when it is called.
119
Yury Selivanov1096f762015-06-25 13:49:52 -0400120 An instance of :class:`asyncio.Handle` is returned, which can be
121 used to cancel the callback.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500122
Victor Stinner8464c242014-11-28 13:15:41 +0100123 :ref:`Use functools.partial to pass keywords to the callback
124 <asyncio-pass-keywords>`.
125
Guido van Rossumf68afd82016-08-08 09:41:21 -0700126.. method:: AbstractEventLoop.call_soon_threadsafe(callback, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100127
128 Like :meth:`call_soon`, but thread safe.
129
Victor Stinner83704962015-02-25 14:24:15 +0100130 See the :ref:`concurrency and multithreading <asyncio-multithreading>`
131 section of the documentation.
132
Victor Stinnerea3183f2013-12-03 01:08:00 +0100133
Victor Stinner45b27ed2014-02-01 02:36:43 +0100134.. _asyncio-delayed-calls:
135
Victor Stinnerea3183f2013-12-03 01:08:00 +0100136Delayed calls
137-------------
138
139The event loop has its own internal clock for computing timeouts.
140Which clock is used depends on the (platform-specific) event loop
141implementation; ideally it is a monotonic clock. This will generally be
142a different clock than :func:`time.time`.
143
Victor Stinnerfd9d3742014-02-18 09:37:43 +0100144.. note::
145
146 Timeouts (relative *delay* or absolute *when*) should not exceed one day.
147
Victor Stinner45b27ed2014-02-01 02:36:43 +0100148
Guido van Rossumf68afd82016-08-08 09:41:21 -0700149.. method:: AbstractEventLoop.call_later(delay, callback, *args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100150
151 Arrange for the *callback* to be called after the given *delay*
152 seconds (either an int or float).
153
Yury Selivanov1096f762015-06-25 13:49:52 -0400154 An instance of :class:`asyncio.Handle` is returned, which can be
155 used to cancel the callback.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100156
157 *callback* will be called exactly once per call to :meth:`call_later`.
158 If two callbacks are scheduled for exactly the same time, it is
159 undefined which will be called first.
160
161 The optional positional *args* will be passed to the callback when it
162 is called. If you want the callback to be called with some named
163 arguments, use a closure or :func:`functools.partial`.
164
Victor Stinner8464c242014-11-28 13:15:41 +0100165 :ref:`Use functools.partial to pass keywords to the callback
166 <asyncio-pass-keywords>`.
167
Guido van Rossumf68afd82016-08-08 09:41:21 -0700168.. method:: AbstractEventLoop.call_at(when, callback, *args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100169
170 Arrange for the *callback* to be called at the given absolute timestamp
Berker Peksagb5563992014-11-07 19:51:07 +0200171 *when* (an int or float), using the same time reference as
Guido van Rossumf68afd82016-08-08 09:41:21 -0700172 :meth:`AbstractEventLoop.time`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100173
174 This method's behavior is the same as :meth:`call_later`.
175
Yury Selivanov1096f762015-06-25 13:49:52 -0400176 An instance of :class:`asyncio.Handle` is returned, which can be
177 used to cancel the callback.
178
Victor Stinner8464c242014-11-28 13:15:41 +0100179 :ref:`Use functools.partial to pass keywords to the callback
180 <asyncio-pass-keywords>`.
181
Guido van Rossumf68afd82016-08-08 09:41:21 -0700182.. method:: AbstractEventLoop.time()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100183
184 Return the current time, as a :class:`float` value, according to the
185 event loop's internal clock.
186
Victor Stinner3e09e322013-12-03 01:22:06 +0100187.. seealso::
188
189 The :func:`asyncio.sleep` function.
190
Victor Stinnerea3183f2013-12-03 01:08:00 +0100191
Yury Selivanov950204d2016-05-16 16:23:00 -0400192Futures
193-------
194
Guido van Rossumf68afd82016-08-08 09:41:21 -0700195.. method:: AbstractEventLoop.create_future()
Yury Selivanov950204d2016-05-16 16:23:00 -0400196
197 Create an :class:`asyncio.Future` object attached to the loop.
198
199 This is a preferred way to create futures in asyncio, as event
200 loop implementations can provide alternative implementations
201 of the Future class (with better performance or instrumentation).
202
203 .. versionadded:: 3.5.2
204
205
Yury Selivanovbb961342015-06-25 11:54:34 -0400206Tasks
207-----
Victor Stinner530ef2f2014-07-08 12:39:10 +0200208
Guido van Rossumf68afd82016-08-08 09:41:21 -0700209.. method:: AbstractEventLoop.create_task(coro)
Victor Stinner530ef2f2014-07-08 12:39:10 +0200210
211 Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in
212 a future. Return a :class:`Task` object.
213
214 Third-party event loops can use their own subclass of :class:`Task` for
215 interoperability. In this case, the result type is a subclass of
216 :class:`Task`.
217
Victor Stinner337e03f2014-08-11 01:11:13 +0200218 This method was added in Python 3.4.2. Use the :func:`async` function to
219 support also older Python versions.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200220
221 .. versionadded:: 3.4.2
222
Guido van Rossumf68afd82016-08-08 09:41:21 -0700223.. method:: AbstractEventLoop.set_task_factory(factory)
Yury Selivanov71854612015-05-11 16:28:27 -0400224
225 Set a task factory that will be used by
Guido van Rossumf68afd82016-08-08 09:41:21 -0700226 :meth:`AbstractEventLoop.create_task`.
Yury Selivanov71854612015-05-11 16:28:27 -0400227
228 If *factory* is ``None`` the default task factory will be set.
229
230 If *factory* is a *callable*, it should have a signature matching
231 ``(loop, coro)``, where *loop* will be a reference to the active
232 event loop, *coro* will be a coroutine object. The callable
233 must return an :class:`asyncio.Future` compatible object.
234
235 .. versionadded:: 3.4.4
236
Guido van Rossumf68afd82016-08-08 09:41:21 -0700237.. method:: AbstractEventLoop.get_task_factory()
Yury Selivanov71854612015-05-11 16:28:27 -0400238
239 Return a task factory, or ``None`` if the default one is in use.
240
241 .. versionadded:: 3.4.4
242
Victor Stinner530ef2f2014-07-08 12:39:10 +0200243
Victor Stinnerea3183f2013-12-03 01:08:00 +0100244Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100245--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100246
Guido van Rossumf68afd82016-08-08 09:41:21 -0700247.. 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 +0100248
249 Create a streaming transport connection to a given Internet *host* and
Victor Stinnera6919aa2014-02-19 13:32:34 +0100250 *port*: socket family :py:data:`~socket.AF_INET` or
251 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
252 socket type :py:data:`~socket.SOCK_STREAM`. *protocol_factory* must be a
253 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100254
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500255 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100256 establish the connection in the background. When successful, the
257 coroutine returns a ``(transport, protocol)`` pair.
258
259 The chronological synopsis of the underlying operation is as follows:
260
Victor Stinner9592edb2014-02-02 15:03:02 +0100261 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100262 is created to represent it.
263
264 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100265 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100266
267 #. The protocol instance is tied to the transport, and its
268 :meth:`connection_made` method is called.
269
270 #. The coroutine returns successfully with the ``(transport, protocol)``
271 pair.
272
273 The created transport is an implementation-dependent bidirectional stream.
274
275 .. note::
276 *protocol_factory* can be any kind of callable, not necessarily
277 a class. For example, if you want to use a pre-created
278 protocol instance, you can pass ``lambda: my_protocol``.
279
Martin Panterc04fb562016-02-10 05:44:01 +0000280 Options that change how the connection is created:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100281
282 * *ssl*: if given and not false, a SSL/TLS transport is created
283 (by default a plain TCP transport is created). If *ssl* is
284 a :class:`ssl.SSLContext` object, this context is used to create
285 the transport; if *ssl* is :const:`True`, a context with some
286 unspecified default settings is used.
287
Berker Peksag9c1dba22014-09-28 00:00:58 +0300288 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100289
Victor Stinnerea3183f2013-12-03 01:08:00 +0100290 * *server_hostname*, is only for use together with *ssl*,
291 and sets or overrides the hostname that the target server's certificate
292 will be matched against. By default the value of the *host* argument
293 is used. If *host* is empty, there is no default and you must pass a
294 value for *server_hostname*. If *server_hostname* is an empty
295 string, hostname matching is disabled (which is a serious security
296 risk, allowing for man-in-the-middle-attacks).
297
298 * *family*, *proto*, *flags* are the optional address family, protocol
299 and flags to be passed through to getaddrinfo() for *host* resolution.
300 If given, these should all be integers from the corresponding
301 :mod:`socket` module constants.
302
303 * *sock*, if given, should be an existing, already connected
304 :class:`socket.socket` object to be used by the transport.
305 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
306 and *local_addr* should be specified.
307
308 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
309 to bind the socket to locally. The *local_host* and *local_port*
310 are looked up using getaddrinfo(), similarly to *host* and *port*.
311
Victor Stinner60208a12015-09-15 22:41:52 +0200312 .. versionchanged:: 3.5
313
314 On Windows with :class:`ProactorEventLoop`, SSL/TLS is now supported.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200315
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100316 .. seealso::
317
318 The :func:`open_connection` function can be used to get a pair of
319 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
320
Victor Stinnerea3183f2013-12-03 01:08:00 +0100321
Guido van Rossumf68afd82016-08-08 09:41:21 -0700322.. 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 +0100323
324 Create datagram connection: socket family :py:data:`~socket.AF_INET` or
325 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700326 socket type :py:data:`~socket.SOCK_DGRAM`. *protocol_factory* must be a
327 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100328
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500329 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100330 establish the connection in the background. When successful, the
331 coroutine returns a ``(transport, protocol)`` pair.
332
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700333 Options changing how the connection is created:
334
335 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
336 to bind the socket to locally. The *local_host* and *local_port*
337 are looked up using :meth:`getaddrinfo`.
338
339 * *remote_addr*, if given, is a ``(remote_host, remote_port)`` tuple used
340 to connect the socket to a remote address. The *remote_host* and
341 *remote_port* are looked up using :meth:`getaddrinfo`.
342
343 * *family*, *proto*, *flags* are the optional address family, protocol
344 and flags to be passed through to :meth:`getaddrinfo` for *host*
345 resolution. If given, these should all be integers from the
346 corresponding :mod:`socket` module constants.
347
348 * *reuse_address* tells the kernel to reuse a local socket in
349 TIME_WAIT state, without waiting for its natural timeout to
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300350 expire. If not specified will automatically be set to ``True`` on
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700351 UNIX.
352
353 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
354 same port as other existing endpoints are bound to, so long as they all
355 set this flag when being created. This option is not supported on Windows
356 and some UNIX's. If the :py:data:`~socket.SO_REUSEPORT` constant is not
357 defined then this capability is unsupported.
358
359 * *allow_broadcast* tells the kernel to allow this endpoint to send
360 messages to the broadcast address.
361
362 * *sock* can optionally be specified in order to use a preexisting,
363 already connected, :class:`socket.socket` object to be used by the
364 transport. If specified, *local_addr* and *remote_addr* should be omitted
365 (must be :const:`None`).
Victor Stinnera6919aa2014-02-19 13:32:34 +0100366
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200367 On Windows with :class:`ProactorEventLoop`, this method is not supported.
368
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200369 See :ref:`UDP echo client protocol <asyncio-udp-echo-client-protocol>` and
370 :ref:`UDP echo server protocol <asyncio-udp-echo-server-protocol>` examples.
371
Victor Stinnera6919aa2014-02-19 13:32:34 +0100372
Guido van Rossumf68afd82016-08-08 09:41:21 -0700373.. coroutinemethod:: AbstractEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
Victor Stinnera6919aa2014-02-19 13:32:34 +0100374
375 Create UNIX connection: socket family :py:data:`~socket.AF_UNIX`, socket
376 type :py:data:`~socket.SOCK_STREAM`. The :py:data:`~socket.AF_UNIX` socket
377 family is used to communicate between processes on the same machine
378 efficiently.
379
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500380 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100381 establish the connection in the background. When successful, the
382 coroutine returns a ``(transport, protocol)`` pair.
383
Guido van Rossum9e80eeb2016-11-03 14:17:25 -0700384 *path* is the name of a UNIX domain socket, and is required unless a *sock*
385 parameter is specified. Abstract UNIX sockets, :class:`str`, and
386 :class:`bytes` paths are supported.
387
Guido van Rossumf68afd82016-08-08 09:41:21 -0700388 See the :meth:`AbstractEventLoop.create_connection` method for parameters.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100389
390 Availability: UNIX.
391
392
Victor Stinnerea3183f2013-12-03 01:08:00 +0100393Creating listening connections
394------------------------------
395
Guido van Rossumf68afd82016-08-08 09:41:21 -0700396.. 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 +0100397
Victor Stinner33f6abe2014-10-12 20:36:04 +0200398 Create a TCP server (socket type :data:`~socket.SOCK_STREAM`) bound to
399 *host* and *port*.
400
401 Return a :class:`Server` object, its :attr:`~Server.sockets` attribute
402 contains created sockets. Use the :meth:`Server.close` method to stop the
403 server: close listening sockets.
404
405 Parameters:
406
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200407 * The *host* parameter can be a string, in that case the TCP server is
408 bound to *host* and *port*. The *host* parameter can also be a sequence
409 of strings and in that case the TCP server is bound to all hosts of the
410 sequence. If *host* is an empty string or ``None``, all interfaces are
411 assumed and a list of multiple sockets will be returned (most likely one
412 for IPv4 and another one for IPv6).
Victor Stinner33f6abe2014-10-12 20:36:04 +0200413
414 * *family* can be set to either :data:`socket.AF_INET` or
415 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
416 it will be determined from host (defaults to :data:`socket.AF_UNSPEC`).
417
418 * *flags* is a bitmask for :meth:`getaddrinfo`.
419
420 * *sock* can optionally be specified in order to use a preexisting
421 socket object. If specified, *host* and *port* should be omitted (must be
422 :const:`None`).
423
424 * *backlog* is the maximum number of queued connections passed to
425 :meth:`~socket.socket.listen` (defaults to 100).
426
427 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the
428 accepted connections.
429
430 * *reuse_address* tells the kernel to reuse a local socket in
431 TIME_WAIT state, without waiting for its natural timeout to
Serhiy Storchaka4adf01c2016-10-19 18:30:05 +0300432 expire. If not specified will automatically be set to ``True`` on
Victor Stinner33f6abe2014-10-12 20:36:04 +0200433 UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100434
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700435 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
436 same port as other existing endpoints are bound to, so long as they all
437 set this flag when being created. This option is not supported on
438 Windows.
439
Victor Stinnerd1432092014-06-19 17:11:49 +0200440 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100441
Victor Stinner60208a12015-09-15 22:41:52 +0200442 .. versionchanged:: 3.5
443
444 On Windows with :class:`ProactorEventLoop`, SSL/TLS is now supported.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200445
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100446 .. seealso::
447
448 The function :func:`start_server` creates a (:class:`StreamReader`,
449 :class:`StreamWriter`) pair and calls back a function with this pair.
450
Victor Stinner7b58a2b2015-09-21 18:41:05 +0200451 .. versionchanged:: 3.5.1
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200452
453 The *host* parameter can now be a sequence of strings.
454
Victor Stinnerea3183f2013-12-03 01:08:00 +0100455
Guido van Rossumf68afd82016-08-08 09:41:21 -0700456.. coroutinemethod:: AbstractEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100457
Guido van Rossumf68afd82016-08-08 09:41:21 -0700458 Similar to :meth:`AbstractEventLoop.create_server`, but specific to the
Victor Stinnera6919aa2014-02-19 13:32:34 +0100459 socket family :py:data:`~socket.AF_UNIX`.
460
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100461 This method is a :ref:`coroutine <coroutine>`.
462
Victor Stinnera6919aa2014-02-19 13:32:34 +0100463 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100464
Yury Selivanov3b3a1412016-11-07 15:35:25 -0500465.. coroutinemethod:: BaseEventLoop.connect_accepted_socket(protocol_factory, sock, \*, ssl=None)
466
467 Handle an accepted connection.
468
469 This is used by servers that accept connections outside of
470 asyncio but that use asyncio to handle them.
471
472 Parameters:
473
474 * *sock* is a preexisting socket object returned from an ``accept``
475 call.
476
477 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the
478 accepted connections.
479
480 This method is a :ref:`coroutine <coroutine>`. When completed, the
481 coroutine returns a ``(transport, protocol)`` pair.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100482
Victor Stinnerc1567df2014-02-08 23:22:58 +0100483Watch file descriptors
484----------------------
485
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200486On Windows with :class:`SelectorEventLoop`, only socket handles are supported
487(ex: pipe file descriptors are not supported).
488
489On Windows with :class:`ProactorEventLoop`, these methods are not supported.
490
Guido van Rossumf68afd82016-08-08 09:41:21 -0700491.. method:: AbstractEventLoop.add_reader(fd, callback, \*args)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100492
493 Start watching the file descriptor for read availability and then call the
494 *callback* with specified arguments.
495
Victor Stinner8464c242014-11-28 13:15:41 +0100496 :ref:`Use functools.partial to pass keywords to the callback
497 <asyncio-pass-keywords>`.
498
Guido van Rossumf68afd82016-08-08 09:41:21 -0700499.. method:: AbstractEventLoop.remove_reader(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100500
501 Stop watching the file descriptor for read availability.
502
Guido van Rossumf68afd82016-08-08 09:41:21 -0700503.. method:: AbstractEventLoop.add_writer(fd, callback, \*args)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100504
505 Start watching the file descriptor for write availability and then call the
506 *callback* with specified arguments.
507
Victor Stinner8464c242014-11-28 13:15:41 +0100508 :ref:`Use functools.partial to pass keywords to the callback
509 <asyncio-pass-keywords>`.
510
Guido van Rossumf68afd82016-08-08 09:41:21 -0700511.. method:: AbstractEventLoop.remove_writer(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100512
513 Stop watching the file descriptor for write availability.
514
Victor Stinner04e6df32014-10-11 16:16:27 +0200515The :ref:`watch a file descriptor for read events <asyncio-watch-read-event>`
Guido van Rossumf68afd82016-08-08 09:41:21 -0700516example uses the low-level :meth:`AbstractEventLoop.add_reader` method to register
Victor Stinner04e6df32014-10-11 16:16:27 +0200517the file descriptor of a socket.
518
Victor Stinnerc1567df2014-02-08 23:22:58 +0100519
520Low-level socket operations
521---------------------------
522
Guido van Rossumf68afd82016-08-08 09:41:21 -0700523.. coroutinemethod:: AbstractEventLoop.sock_recv(sock, nbytes)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100524
Yury Selivanov55c50842016-06-08 12:48:15 -0400525 Receive data from the socket. Modeled after blocking
526 :meth:`socket.socket.recv` method.
527
528 The return value is a bytes object
Victor Stinnerc1567df2014-02-08 23:22:58 +0100529 representing the data received. The maximum amount of data to be received
530 at once is specified by *nbytes*.
531
Victor Stinnerd84fd732014-08-26 01:01:59 +0200532 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
533 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200534
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500535 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100536
Guido van Rossumf68afd82016-08-08 09:41:21 -0700537.. coroutinemethod:: AbstractEventLoop.sock_sendall(sock, data)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100538
Yury Selivanov55c50842016-06-08 12:48:15 -0400539 Send data to the socket. Modeled after blocking
540 :meth:`socket.socket.sendall` method.
541
542 The socket must be connected to a remote socket.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100543 This method continues to send data from *data* until either all data has
544 been sent or an error occurs. ``None`` is returned on success. On error,
545 an exception is raised, and there is no way to determine how much data, if
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500546 any, was successfully processed by the receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100547
Victor Stinnerd84fd732014-08-26 01:01:59 +0200548 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
549 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200550
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500551 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100552
Guido van Rossumf68afd82016-08-08 09:41:21 -0700553.. coroutinemethod:: AbstractEventLoop.sock_connect(sock, address)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100554
Yury Selivanov55c50842016-06-08 12:48:15 -0400555 Connect to a remote socket at *address*. Modeled after
556 blocking :meth:`socket.socket.connect` method.
Victor Stinner1b0580b2014-02-13 09:24:37 +0100557
Victor Stinnerd84fd732014-08-26 01:01:59 +0200558 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
559 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200560
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500561 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100562
Yury Selivanov55c50842016-06-08 12:48:15 -0400563 .. versionchanged:: 3.5.2
564 ``address`` no longer needs to be resolved. ``sock_connect``
565 will try to check if the *address* is already resolved by calling
566 :func:`socket.inet_pton`. If not,
Guido van Rossumf68afd82016-08-08 09:41:21 -0700567 :meth:`AbstractEventLoop.getaddrinfo` will be used to resolve the
Yury Selivanov55c50842016-06-08 12:48:15 -0400568 *address*.
569
Victor Stinnerc1567df2014-02-08 23:22:58 +0100570 .. seealso::
571
Guido van Rossumf68afd82016-08-08 09:41:21 -0700572 :meth:`AbstractEventLoop.create_connection`
Yury Selivanov55c50842016-06-08 12:48:15 -0400573 and :func:`asyncio.open_connection() <open_connection>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100574
575
Guido van Rossumf68afd82016-08-08 09:41:21 -0700576.. coroutinemethod:: AbstractEventLoop.sock_accept(sock)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100577
Yury Selivanov55c50842016-06-08 12:48:15 -0400578 Accept a connection. Modeled after blocking
579 :meth:`socket.socket.accept`.
580
581 The socket must be bound to an address and listening
Victor Stinnerc1567df2014-02-08 23:22:58 +0100582 for connections. The return value is a pair ``(conn, address)`` where *conn*
583 is a *new* socket object usable to send and receive data on the connection,
584 and *address* is the address bound to the socket on the other end of the
585 connection.
586
Victor Stinnerec2ce092014-07-29 23:12:22 +0200587 The socket *sock* must be non-blocking.
588
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500589 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100590
591 .. seealso::
592
Guido van Rossumf68afd82016-08-08 09:41:21 -0700593 :meth:`AbstractEventLoop.create_server` and :func:`start_server`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100594
595
596Resolve host name
597-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100598
Guido van Rossumf68afd82016-08-08 09:41:21 -0700599.. coroutinemethod:: AbstractEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100600
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500601 This method is a :ref:`coroutine <coroutine>`, similar to
602 :meth:`socket.getaddrinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100603
Guido van Rossumf68afd82016-08-08 09:41:21 -0700604.. coroutinemethod:: AbstractEventLoop.getnameinfo(sockaddr, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100605
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500606 This method is a :ref:`coroutine <coroutine>`, similar to
607 :meth:`socket.getnameinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100608
609
Victor Stinner984600f2014-03-25 09:40:26 +0100610Connect pipes
611-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100612
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200613On Windows with :class:`SelectorEventLoop`, these methods are not supported.
614Use :class:`ProactorEventLoop` to support pipes on Windows.
615
Guido van Rossumf68afd82016-08-08 09:41:21 -0700616.. coroutinemethod:: AbstractEventLoop.connect_read_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100617
Victor Stinnerd84fd732014-08-26 01:01:59 +0200618 Register read pipe in eventloop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100619
620 *protocol_factory* should instantiate object with :class:`Protocol`
Victor Stinnera5b257a2014-05-29 00:14:03 +0200621 interface. *pipe* is a :term:`file-like object <file object>`.
622 Return pair ``(transport, protocol)``, where *transport* supports the
Victor Stinnerea3183f2013-12-03 01:08:00 +0100623 :class:`ReadTransport` interface.
624
Victor Stinnerd84fd732014-08-26 01:01:59 +0200625 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
626 non-blocking mode.
627
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500628 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100629
Guido van Rossumf68afd82016-08-08 09:41:21 -0700630.. coroutinemethod:: AbstractEventLoop.connect_write_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100631
632 Register write pipe in eventloop.
633
634 *protocol_factory* should instantiate object with :class:`BaseProtocol`
Victor Stinner2cef3002014-10-23 22:38:46 +0200635 interface. *pipe* is :term:`file-like object <file object>`.
636 Return pair ``(transport, protocol)``, where *transport* supports
Victor Stinnerea3183f2013-12-03 01:08:00 +0100637 :class:`WriteTransport` interface.
638
Victor Stinnerd84fd732014-08-26 01:01:59 +0200639 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
640 non-blocking mode.
641
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500642 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100643
Victor Stinner08444382014-02-02 22:43:39 +0100644.. seealso::
645
Guido van Rossumf68afd82016-08-08 09:41:21 -0700646 The :meth:`AbstractEventLoop.subprocess_exec` and
647 :meth:`AbstractEventLoop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100648
Victor Stinnerea3183f2013-12-03 01:08:00 +0100649
Victor Stinner8b863482014-01-27 10:07:50 +0100650UNIX signals
651------------
652
653Availability: UNIX only.
654
Guido van Rossumf68afd82016-08-08 09:41:21 -0700655.. method:: AbstractEventLoop.add_signal_handler(signum, callback, \*args)
Victor Stinner8b863482014-01-27 10:07:50 +0100656
657 Add a handler for a signal.
658
659 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
660 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
661
Victor Stinner8464c242014-11-28 13:15:41 +0100662 :ref:`Use functools.partial to pass keywords to the callback
663 <asyncio-pass-keywords>`.
664
Guido van Rossumf68afd82016-08-08 09:41:21 -0700665.. method:: AbstractEventLoop.remove_signal_handler(sig)
Victor Stinner8b863482014-01-27 10:07:50 +0100666
667 Remove a handler for a signal.
668
669 Return ``True`` if a signal handler was removed, ``False`` if not.
670
671.. seealso::
672
673 The :mod:`signal` module.
674
675
Victor Stinnerea3183f2013-12-03 01:08:00 +0100676Executor
677--------
678
679Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
680pool of processes). By default, an event loop uses a thread pool executor
681(:class:`~concurrent.futures.ThreadPoolExecutor`).
682
Guido van Rossumf68afd82016-08-08 09:41:21 -0700683.. coroutinemethod:: AbstractEventLoop.run_in_executor(executor, func, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100684
Andrew Svetlov1c62b522015-10-01 09:48:08 +0300685 Arrange for a *func* to be called in the specified executor.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100686
Larry Hastings3732ed22014-03-15 21:13:56 -0700687 The *executor* argument should be an :class:`~concurrent.futures.Executor`
688 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100689
Andrew Svetlov1c62b522015-10-01 09:48:08 +0300690 :ref:`Use functools.partial to pass keywords to the *func*
Victor Stinner8464c242014-11-28 13:15:41 +0100691 <asyncio-pass-keywords>`.
692
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500693 This method is a :ref:`coroutine <coroutine>`.
694
Yury Selivanove8a60452016-10-21 17:40:42 -0400695 .. versionchanged:: 3.5.3
696 :meth:`BaseEventLoop.run_in_executor` no longer configures the
697 ``max_workers`` of the thread pool executor it creates, instead
698 leaving it up to the thread pool executor
699 (:class:`~concurrent.futures.ThreadPoolExecutor`) to set the
700 default.
701
Guido van Rossumf68afd82016-08-08 09:41:21 -0700702.. method:: AbstractEventLoop.set_default_executor(executor)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100703
704 Set the default executor used by :meth:`run_in_executor`.
705
706
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500707Error Handling API
708------------------
709
Martin Panterc04fb562016-02-10 05:44:01 +0000710Allows customizing how exceptions are handled in the event loop.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500711
Guido van Rossumf68afd82016-08-08 09:41:21 -0700712.. method:: AbstractEventLoop.set_exception_handler(handler)
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500713
714 Set *handler* as the new event loop exception handler.
715
716 If *handler* is ``None``, the default exception handler will
717 be set.
718
719 If *handler* is a callable object, it should have a
720 matching signature to ``(loop, context)``, where ``loop``
721 will be a reference to the active event loop, ``context``
722 will be a ``dict`` object (see :meth:`call_exception_handler`
723 documentation for details about context).
724
Guido van Rossumf68afd82016-08-08 09:41:21 -0700725.. method:: AbstractEventLoop.get_exception_handler()
Yury Selivanov950204d2016-05-16 16:23:00 -0400726
727 Return the exception handler, or ``None`` if the default one
728 is in use.
729
730 .. versionadded:: 3.5.2
731
Guido van Rossumf68afd82016-08-08 09:41:21 -0700732.. method:: AbstractEventLoop.default_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500733
734 Default exception handler.
735
736 This is called when an exception occurs and no exception
737 handler is set, and can be called by a custom exception
738 handler that wants to defer to the default behavior.
739
740 *context* parameter has the same meaning as in
741 :meth:`call_exception_handler`.
742
Guido van Rossumf68afd82016-08-08 09:41:21 -0700743.. method:: AbstractEventLoop.call_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500744
745 Call the current event loop exception handler.
746
747 *context* is a ``dict`` object containing the following keys
748 (new keys may be introduced later):
749
750 * 'message': Error message;
751 * 'exception' (optional): Exception object;
752 * 'future' (optional): :class:`asyncio.Future` instance;
753 * 'handle' (optional): :class:`asyncio.Handle` instance;
754 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
755 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
756 * 'socket' (optional): :class:`socket.socket` instance.
757
758 .. note::
759
760 Note: this method should not be overloaded in subclassed
761 event loops. For any custom exception handling, use
762 :meth:`set_exception_handler()` method.
763
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100764Debug mode
765----------
766
Guido van Rossumf68afd82016-08-08 09:41:21 -0700767.. method:: AbstractEventLoop.get_debug()
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100768
Victor Stinner7b7120e2014-06-23 00:12:14 +0200769 Get the debug mode (:class:`bool`) of the event loop.
770
771 The default value is ``True`` if the environment variable
772 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
773 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100774
Victor Stinner64d750b2014-06-18 03:25:23 +0200775 .. versionadded:: 3.4.2
776
Guido van Rossumf68afd82016-08-08 09:41:21 -0700777.. method:: AbstractEventLoop.set_debug(enabled: bool)
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100778
779 Set the debug mode of the event loop.
780
Victor Stinner64d750b2014-06-18 03:25:23 +0200781 .. versionadded:: 3.4.2
782
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100783.. seealso::
784
Victor Stinner62511fd2014-06-23 00:36:11 +0200785 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100786
Victor Stinner8c462c52014-01-24 18:11:43 +0100787Server
788------
789
Victor Stinner8ebeb032014-07-11 23:47:40 +0200790.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +0100791
Victor Stinner8ebeb032014-07-11 23:47:40 +0200792 Server listening on sockets.
793
Guido van Rossumf68afd82016-08-08 09:41:21 -0700794 Object created by the :meth:`AbstractEventLoop.create_server` method and the
R David Murray756f0b12015-01-29 19:53:33 -0500795 :func:`start_server` function. Don't instantiate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +0100796
797 .. method:: close()
798
Victor Stinner4bfb14a2014-07-12 03:20:24 +0200799 Stop serving: close listening sockets and set the :attr:`sockets`
800 attribute to ``None``.
801
Berker Peksag49c9edf2016-01-20 07:14:22 +0200802 The sockets that represent existing incoming client connections are left
803 open.
Victor Stinner8ebeb032014-07-11 23:47:40 +0200804
Berker Peksag49c9edf2016-01-20 07:14:22 +0200805 The server is closed asynchronously, use the :meth:`wait_closed`
806 coroutine to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100807
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100808 .. coroutinemethod:: wait_closed()
Victor Stinner8c462c52014-01-24 18:11:43 +0100809
Victor Stinner8ebeb032014-07-11 23:47:40 +0200810 Wait until the :meth:`close` method completes.
811
812 This method is a :ref:`coroutine <coroutine>`.
813
814 .. attribute:: sockets
815
816 List of :class:`socket.socket` objects the server is listening to, or
817 ``None`` if the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100818
819
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500820Handle
821------
822
823.. class:: Handle
824
Guido van Rossumf68afd82016-08-08 09:41:21 -0700825 A callback wrapper object returned by :func:`AbstractEventLoop.call_soon`,
826 :func:`AbstractEventLoop.call_soon_threadsafe`, :func:`AbstractEventLoop.call_later`,
827 and :func:`AbstractEventLoop.call_at`.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500828
829 .. method:: cancel()
830
Yury Selivanov1096f762015-06-25 13:49:52 -0400831 Cancel the call. If the callback is already canceled or executed,
832 this method has no effect.
Victor Stinneraea82292014-07-08 23:42:38 +0200833
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500834
Victor Stinner6888b962014-10-11 16:15:58 +0200835Event loop examples
Victor Stinnera092a612015-01-09 15:58:41 +0100836-------------------
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500837
Victor Stinner3e09e322013-12-03 01:22:06 +0100838.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100839
Victor Stinner7f314ed2014-10-15 18:49:16 +0200840Hello World with call_soon()
Victor Stinnera092a612015-01-09 15:58:41 +0100841^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100842
Guido van Rossumf68afd82016-08-08 09:41:21 -0700843Example using the :meth:`AbstractEventLoop.call_soon` method to schedule a
Victor Stinner7f314ed2014-10-15 18:49:16 +0200844callback. The callback displays ``"Hello World"`` and then stops the event
845loop::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100846
847 import asyncio
848
Victor Stinner7f314ed2014-10-15 18:49:16 +0200849 def hello_world(loop):
Victor Stinnerea3183f2013-12-03 01:08:00 +0100850 print('Hello World')
Victor Stinner7f314ed2014-10-15 18:49:16 +0200851 loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100852
853 loop = asyncio.get_event_loop()
Victor Stinner7f314ed2014-10-15 18:49:16 +0200854
855 # Schedule a call to hello_world()
856 loop.call_soon(hello_world, loop)
857
858 # Blocking call interrupted by loop.stop()
859 loop.run_forever()
860 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100861
Victor Stinner3e09e322013-12-03 01:22:06 +0100862.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100863
Victor Stinner6888b962014-10-11 16:15:58 +0200864 The :ref:`Hello World coroutine <asyncio-hello-world-coroutine>` example
865 uses a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100866
Victor Stinner8b863482014-01-27 10:07:50 +0100867
Victor Stinner7f314ed2014-10-15 18:49:16 +0200868.. _asyncio-date-callback:
869
870Display the current date with call_later()
Victor Stinnera092a612015-01-09 15:58:41 +0100871^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner7f314ed2014-10-15 18:49:16 +0200872
873Example of callback displaying the current date every second. The callback uses
Guido van Rossumf68afd82016-08-08 09:41:21 -0700874the :meth:`AbstractEventLoop.call_later` method to reschedule itself during 5
Victor Stinner7f314ed2014-10-15 18:49:16 +0200875seconds, and then stops the event loop::
876
877 import asyncio
878 import datetime
879
880 def display_date(end_time, loop):
881 print(datetime.datetime.now())
882 if (loop.time() + 1.0) < end_time:
883 loop.call_later(1, display_date, end_time, loop)
884 else:
885 loop.stop()
886
887 loop = asyncio.get_event_loop()
888
889 # Schedule the first call to display_date()
890 end_time = loop.time() + 5.0
891 loop.call_soon(display_date, end_time, loop)
892
893 # Blocking call interrupted by loop.stop()
894 loop.run_forever()
895 loop.close()
896
897.. seealso::
898
899 The :ref:`coroutine displaying the current date
900 <asyncio-date-coroutine>` example uses a :ref:`coroutine
901 <coroutine>`.
902
903
Victor Stinner04e6df32014-10-11 16:16:27 +0200904.. _asyncio-watch-read-event:
Victor Stinner8b863482014-01-27 10:07:50 +0100905
Victor Stinner04e6df32014-10-11 16:16:27 +0200906Watch a file descriptor for read events
Victor Stinnera092a612015-01-09 15:58:41 +0100907^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +0200908
909Wait until a file descriptor received some data using the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700910:meth:`AbstractEventLoop.add_reader` method and then close the event loop::
Victor Stinner04e6df32014-10-11 16:16:27 +0200911
912 import asyncio
Victor Stinnerccd8e342014-10-11 16:30:02 +0200913 try:
914 from socket import socketpair
915 except ImportError:
916 from asyncio.windows_utils import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +0200917
918 # Create a pair of connected file descriptors
Victor Stinnerccd8e342014-10-11 16:30:02 +0200919 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200920 loop = asyncio.get_event_loop()
921
922 def reader():
923 data = rsock.recv(100)
924 print("Received:", data.decode())
Victor Stinner2cef3002014-10-23 22:38:46 +0200925 # We are done: unregister the file descriptor
Victor Stinner04e6df32014-10-11 16:16:27 +0200926 loop.remove_reader(rsock)
927 # Stop the event loop
928 loop.stop()
929
Victor Stinner2cef3002014-10-23 22:38:46 +0200930 # Register the file descriptor for read event
Victor Stinner04e6df32014-10-11 16:16:27 +0200931 loop.add_reader(rsock, reader)
932
933 # Simulate the reception of data from the network
934 loop.call_soon(wsock.send, 'abc'.encode())
935
936 # Run the event loop
937 loop.run_forever()
938
939 # We are done, close sockets and the event loop
940 rsock.close()
941 wsock.close()
942 loop.close()
943
944.. seealso::
945
946 The :ref:`register an open socket to wait for data using a protocol
947 <asyncio-register-socket>` example uses a low-level protocol created by the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700948 :meth:`AbstractEventLoop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200949
950 The :ref:`register an open socket to wait for data using streams
951 <asyncio-register-socket-streams>` example uses high-level streams
952 created by the :func:`open_connection` function in a coroutine.
953
954
955Set signal handlers for SIGINT and SIGTERM
Victor Stinnera092a612015-01-09 15:58:41 +0100956^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +0200957
958Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM` using
Guido van Rossumf68afd82016-08-08 09:41:21 -0700959the :meth:`AbstractEventLoop.add_signal_handler` method::
Victor Stinner8b863482014-01-27 10:07:50 +0100960
961 import asyncio
962 import functools
963 import os
964 import signal
965
966 def ask_exit(signame):
967 print("got signal %s: exit" % signame)
968 loop.stop()
969
970 loop = asyncio.get_event_loop()
971 for signame in ('SIGINT', 'SIGTERM'):
972 loop.add_signal_handler(getattr(signal, signame),
973 functools.partial(ask_exit, signame))
974
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300975 print("Event loop running forever, press Ctrl+C to interrupt.")
Victor Stinner8b863482014-01-27 10:07:50 +0100976 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
Victor Stinner63b21a82014-07-05 15:38:59 +0200977 try:
978 loop.run_forever()
979 finally:
980 loop.close()
Victor Stinner2cef3002014-10-23 22:38:46 +0200981
982This example only works on UNIX.