blob: 6706001553ee9c891a0e776042316676849bde7a [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
350 expire. If not specified will automatically be set to True on
351 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 Rossumf68afd82016-08-08 09:41:21 -0700384 See the :meth:`AbstractEventLoop.create_connection` method for parameters.
Victor Stinnera6919aa2014-02-19 13:32:34 +0100385
386 Availability: UNIX.
387
388
Victor Stinnerea3183f2013-12-03 01:08:00 +0100389Creating listening connections
390------------------------------
391
Guido van Rossumf68afd82016-08-08 09:41:21 -0700392.. 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 +0100393
Victor Stinner33f6abe2014-10-12 20:36:04 +0200394 Create a TCP server (socket type :data:`~socket.SOCK_STREAM`) bound to
395 *host* and *port*.
396
397 Return a :class:`Server` object, its :attr:`~Server.sockets` attribute
398 contains created sockets. Use the :meth:`Server.close` method to stop the
399 server: close listening sockets.
400
401 Parameters:
402
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200403 * The *host* parameter can be a string, in that case the TCP server is
404 bound to *host* and *port*. The *host* parameter can also be a sequence
405 of strings and in that case the TCP server is bound to all hosts of the
406 sequence. If *host* is an empty string or ``None``, all interfaces are
407 assumed and a list of multiple sockets will be returned (most likely one
408 for IPv4 and another one for IPv6).
Victor Stinner33f6abe2014-10-12 20:36:04 +0200409
410 * *family* can be set to either :data:`socket.AF_INET` or
411 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
412 it will be determined from host (defaults to :data:`socket.AF_UNSPEC`).
413
414 * *flags* is a bitmask for :meth:`getaddrinfo`.
415
416 * *sock* can optionally be specified in order to use a preexisting
417 socket object. If specified, *host* and *port* should be omitted (must be
418 :const:`None`).
419
420 * *backlog* is the maximum number of queued connections passed to
421 :meth:`~socket.socket.listen` (defaults to 100).
422
423 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the
424 accepted connections.
425
426 * *reuse_address* tells the kernel to reuse a local socket in
427 TIME_WAIT state, without waiting for its natural timeout to
428 expire. If not specified will automatically be set to True on
429 UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100430
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700431 * *reuse_port* tells the kernel to allow this endpoint to be bound to the
432 same port as other existing endpoints are bound to, so long as they all
433 set this flag when being created. This option is not supported on
434 Windows.
435
Victor Stinnerd1432092014-06-19 17:11:49 +0200436 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100437
Victor Stinner60208a12015-09-15 22:41:52 +0200438 .. versionchanged:: 3.5
439
440 On Windows with :class:`ProactorEventLoop`, SSL/TLS is now supported.
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200441
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100442 .. seealso::
443
444 The function :func:`start_server` creates a (:class:`StreamReader`,
445 :class:`StreamWriter`) pair and calls back a function with this pair.
446
Victor Stinner7b58a2b2015-09-21 18:41:05 +0200447 .. versionchanged:: 3.5.1
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200448
449 The *host* parameter can now be a sequence of strings.
450
Victor Stinnerea3183f2013-12-03 01:08:00 +0100451
Guido van Rossumf68afd82016-08-08 09:41:21 -0700452.. coroutinemethod:: AbstractEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100453
Guido van Rossumf68afd82016-08-08 09:41:21 -0700454 Similar to :meth:`AbstractEventLoop.create_server`, but specific to the
Victor Stinnera6919aa2014-02-19 13:32:34 +0100455 socket family :py:data:`~socket.AF_UNIX`.
456
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100457 This method is a :ref:`coroutine <coroutine>`.
458
Victor Stinnera6919aa2014-02-19 13:32:34 +0100459 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100460
461
Victor Stinnerc1567df2014-02-08 23:22:58 +0100462Watch file descriptors
463----------------------
464
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200465On Windows with :class:`SelectorEventLoop`, only socket handles are supported
466(ex: pipe file descriptors are not supported).
467
468On Windows with :class:`ProactorEventLoop`, these methods are not supported.
469
Guido van Rossumf68afd82016-08-08 09:41:21 -0700470.. method:: AbstractEventLoop.add_reader(fd, callback, \*args)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100471
472 Start watching the file descriptor for read availability and then call the
473 *callback* with specified arguments.
474
Victor Stinner8464c242014-11-28 13:15:41 +0100475 :ref:`Use functools.partial to pass keywords to the callback
476 <asyncio-pass-keywords>`.
477
Guido van Rossumf68afd82016-08-08 09:41:21 -0700478.. method:: AbstractEventLoop.remove_reader(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100479
480 Stop watching the file descriptor for read availability.
481
Guido van Rossumf68afd82016-08-08 09:41:21 -0700482.. method:: AbstractEventLoop.add_writer(fd, callback, \*args)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100483
484 Start watching the file descriptor for write availability and then call the
485 *callback* with specified arguments.
486
Victor Stinner8464c242014-11-28 13:15:41 +0100487 :ref:`Use functools.partial to pass keywords to the callback
488 <asyncio-pass-keywords>`.
489
Guido van Rossumf68afd82016-08-08 09:41:21 -0700490.. method:: AbstractEventLoop.remove_writer(fd)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100491
492 Stop watching the file descriptor for write availability.
493
Victor Stinner04e6df32014-10-11 16:16:27 +0200494The :ref:`watch a file descriptor for read events <asyncio-watch-read-event>`
Guido van Rossumf68afd82016-08-08 09:41:21 -0700495example uses the low-level :meth:`AbstractEventLoop.add_reader` method to register
Victor Stinner04e6df32014-10-11 16:16:27 +0200496the file descriptor of a socket.
497
Victor Stinnerc1567df2014-02-08 23:22:58 +0100498
499Low-level socket operations
500---------------------------
501
Guido van Rossumf68afd82016-08-08 09:41:21 -0700502.. coroutinemethod:: AbstractEventLoop.sock_recv(sock, nbytes)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100503
Yury Selivanov55c50842016-06-08 12:48:15 -0400504 Receive data from the socket. Modeled after blocking
505 :meth:`socket.socket.recv` method.
506
507 The return value is a bytes object
Victor Stinnerc1567df2014-02-08 23:22:58 +0100508 representing the data received. The maximum amount of data to be received
509 at once is specified by *nbytes*.
510
Victor Stinnerd84fd732014-08-26 01:01:59 +0200511 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
512 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200513
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500514 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100515
Guido van Rossumf68afd82016-08-08 09:41:21 -0700516.. coroutinemethod:: AbstractEventLoop.sock_sendall(sock, data)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100517
Yury Selivanov55c50842016-06-08 12:48:15 -0400518 Send data to the socket. Modeled after blocking
519 :meth:`socket.socket.sendall` method.
520
521 The socket must be connected to a remote socket.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100522 This method continues to send data from *data* until either all data has
523 been sent or an error occurs. ``None`` is returned on success. On error,
524 an exception is raised, and there is no way to determine how much data, if
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500525 any, was successfully processed by the receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100526
Victor Stinnerd84fd732014-08-26 01:01:59 +0200527 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
528 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200529
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500530 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100531
Guido van Rossumf68afd82016-08-08 09:41:21 -0700532.. coroutinemethod:: AbstractEventLoop.sock_connect(sock, address)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100533
Yury Selivanov55c50842016-06-08 12:48:15 -0400534 Connect to a remote socket at *address*. Modeled after
535 blocking :meth:`socket.socket.connect` method.
Victor Stinner1b0580b2014-02-13 09:24:37 +0100536
Victor Stinnerd84fd732014-08-26 01:01:59 +0200537 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
538 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200539
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500540 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100541
Yury Selivanov55c50842016-06-08 12:48:15 -0400542 .. versionchanged:: 3.5.2
543 ``address`` no longer needs to be resolved. ``sock_connect``
544 will try to check if the *address* is already resolved by calling
545 :func:`socket.inet_pton`. If not,
Guido van Rossumf68afd82016-08-08 09:41:21 -0700546 :meth:`AbstractEventLoop.getaddrinfo` will be used to resolve the
Yury Selivanov55c50842016-06-08 12:48:15 -0400547 *address*.
548
Victor Stinnerc1567df2014-02-08 23:22:58 +0100549 .. seealso::
550
Guido van Rossumf68afd82016-08-08 09:41:21 -0700551 :meth:`AbstractEventLoop.create_connection`
Yury Selivanov55c50842016-06-08 12:48:15 -0400552 and :func:`asyncio.open_connection() <open_connection>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100553
554
Guido van Rossumf68afd82016-08-08 09:41:21 -0700555.. coroutinemethod:: AbstractEventLoop.sock_accept(sock)
Victor Stinnerc1567df2014-02-08 23:22:58 +0100556
Yury Selivanov55c50842016-06-08 12:48:15 -0400557 Accept a connection. Modeled after blocking
558 :meth:`socket.socket.accept`.
559
560 The socket must be bound to an address and listening
Victor Stinnerc1567df2014-02-08 23:22:58 +0100561 for connections. The return value is a pair ``(conn, address)`` where *conn*
562 is a *new* socket object usable to send and receive data on the connection,
563 and *address* is the address bound to the socket on the other end of the
564 connection.
565
Victor Stinnerec2ce092014-07-29 23:12:22 +0200566 The socket *sock* must be non-blocking.
567
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500568 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100569
570 .. seealso::
571
Guido van Rossumf68afd82016-08-08 09:41:21 -0700572 :meth:`AbstractEventLoop.create_server` and :func:`start_server`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100573
574
575Resolve host name
576-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100577
Guido van Rossumf68afd82016-08-08 09:41:21 -0700578.. coroutinemethod:: AbstractEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100579
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500580 This method is a :ref:`coroutine <coroutine>`, similar to
581 :meth:`socket.getaddrinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100582
Guido van Rossumf68afd82016-08-08 09:41:21 -0700583.. coroutinemethod:: AbstractEventLoop.getnameinfo(sockaddr, flags=0)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100584
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500585 This method is a :ref:`coroutine <coroutine>`, similar to
586 :meth:`socket.getnameinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100587
588
Victor Stinner984600f2014-03-25 09:40:26 +0100589Connect pipes
590-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100591
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200592On Windows with :class:`SelectorEventLoop`, these methods are not supported.
593Use :class:`ProactorEventLoop` to support pipes on Windows.
594
Guido van Rossumf68afd82016-08-08 09:41:21 -0700595.. coroutinemethod:: AbstractEventLoop.connect_read_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100596
Victor Stinnerd84fd732014-08-26 01:01:59 +0200597 Register read pipe in eventloop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100598
599 *protocol_factory* should instantiate object with :class:`Protocol`
Victor Stinnera5b257a2014-05-29 00:14:03 +0200600 interface. *pipe* is a :term:`file-like object <file object>`.
601 Return pair ``(transport, protocol)``, where *transport* supports the
Victor Stinnerea3183f2013-12-03 01:08:00 +0100602 :class:`ReadTransport` interface.
603
Victor Stinnerd84fd732014-08-26 01:01:59 +0200604 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
605 non-blocking mode.
606
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500607 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100608
Guido van Rossumf68afd82016-08-08 09:41:21 -0700609.. coroutinemethod:: AbstractEventLoop.connect_write_pipe(protocol_factory, pipe)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100610
611 Register write pipe in eventloop.
612
613 *protocol_factory* should instantiate object with :class:`BaseProtocol`
Victor Stinner2cef3002014-10-23 22:38:46 +0200614 interface. *pipe* is :term:`file-like object <file object>`.
615 Return pair ``(transport, protocol)``, where *transport* supports
Victor Stinnerea3183f2013-12-03 01:08:00 +0100616 :class:`WriteTransport` interface.
617
Victor Stinnerd84fd732014-08-26 01:01:59 +0200618 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
619 non-blocking mode.
620
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500621 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100622
Victor Stinner08444382014-02-02 22:43:39 +0100623.. seealso::
624
Guido van Rossumf68afd82016-08-08 09:41:21 -0700625 The :meth:`AbstractEventLoop.subprocess_exec` and
626 :meth:`AbstractEventLoop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100627
Victor Stinnerea3183f2013-12-03 01:08:00 +0100628
Victor Stinner8b863482014-01-27 10:07:50 +0100629UNIX signals
630------------
631
632Availability: UNIX only.
633
Guido van Rossumf68afd82016-08-08 09:41:21 -0700634.. method:: AbstractEventLoop.add_signal_handler(signum, callback, \*args)
Victor Stinner8b863482014-01-27 10:07:50 +0100635
636 Add a handler for a signal.
637
638 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
639 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
640
Victor Stinner8464c242014-11-28 13:15:41 +0100641 :ref:`Use functools.partial to pass keywords to the callback
642 <asyncio-pass-keywords>`.
643
Guido van Rossumf68afd82016-08-08 09:41:21 -0700644.. method:: AbstractEventLoop.remove_signal_handler(sig)
Victor Stinner8b863482014-01-27 10:07:50 +0100645
646 Remove a handler for a signal.
647
648 Return ``True`` if a signal handler was removed, ``False`` if not.
649
650.. seealso::
651
652 The :mod:`signal` module.
653
654
Victor Stinnerea3183f2013-12-03 01:08:00 +0100655Executor
656--------
657
658Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
659pool of processes). By default, an event loop uses a thread pool executor
660(:class:`~concurrent.futures.ThreadPoolExecutor`).
661
Guido van Rossumf68afd82016-08-08 09:41:21 -0700662.. coroutinemethod:: AbstractEventLoop.run_in_executor(executor, func, \*args)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100663
Andrew Svetlov1c62b522015-10-01 09:48:08 +0300664 Arrange for a *func* to be called in the specified executor.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100665
Larry Hastings3732ed22014-03-15 21:13:56 -0700666 The *executor* argument should be an :class:`~concurrent.futures.Executor`
667 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100668
Andrew Svetlov1c62b522015-10-01 09:48:08 +0300669 :ref:`Use functools.partial to pass keywords to the *func*
Victor Stinner8464c242014-11-28 13:15:41 +0100670 <asyncio-pass-keywords>`.
671
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500672 This method is a :ref:`coroutine <coroutine>`.
673
Guido van Rossumf68afd82016-08-08 09:41:21 -0700674.. method:: AbstractEventLoop.set_default_executor(executor)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100675
676 Set the default executor used by :meth:`run_in_executor`.
677
678
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500679Error Handling API
680------------------
681
Martin Panterc04fb562016-02-10 05:44:01 +0000682Allows customizing how exceptions are handled in the event loop.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500683
Guido van Rossumf68afd82016-08-08 09:41:21 -0700684.. method:: AbstractEventLoop.set_exception_handler(handler)
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500685
686 Set *handler* as the new event loop exception handler.
687
688 If *handler* is ``None``, the default exception handler will
689 be set.
690
691 If *handler* is a callable object, it should have a
692 matching signature to ``(loop, context)``, where ``loop``
693 will be a reference to the active event loop, ``context``
694 will be a ``dict`` object (see :meth:`call_exception_handler`
695 documentation for details about context).
696
Guido van Rossumf68afd82016-08-08 09:41:21 -0700697.. method:: AbstractEventLoop.get_exception_handler()
Yury Selivanov950204d2016-05-16 16:23:00 -0400698
699 Return the exception handler, or ``None`` if the default one
700 is in use.
701
702 .. versionadded:: 3.5.2
703
Guido van Rossumf68afd82016-08-08 09:41:21 -0700704.. method:: AbstractEventLoop.default_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500705
706 Default exception handler.
707
708 This is called when an exception occurs and no exception
709 handler is set, and can be called by a custom exception
710 handler that wants to defer to the default behavior.
711
712 *context* parameter has the same meaning as in
713 :meth:`call_exception_handler`.
714
Guido van Rossumf68afd82016-08-08 09:41:21 -0700715.. method:: AbstractEventLoop.call_exception_handler(context)
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500716
717 Call the current event loop exception handler.
718
719 *context* is a ``dict`` object containing the following keys
720 (new keys may be introduced later):
721
722 * 'message': Error message;
723 * 'exception' (optional): Exception object;
724 * 'future' (optional): :class:`asyncio.Future` instance;
725 * 'handle' (optional): :class:`asyncio.Handle` instance;
726 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
727 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
728 * 'socket' (optional): :class:`socket.socket` instance.
729
730 .. note::
731
732 Note: this method should not be overloaded in subclassed
733 event loops. For any custom exception handling, use
734 :meth:`set_exception_handler()` method.
735
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100736Debug mode
737----------
738
Guido van Rossumf68afd82016-08-08 09:41:21 -0700739.. method:: AbstractEventLoop.get_debug()
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100740
Victor Stinner7b7120e2014-06-23 00:12:14 +0200741 Get the debug mode (:class:`bool`) of the event loop.
742
743 The default value is ``True`` if the environment variable
744 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
745 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100746
Victor Stinner64d750b2014-06-18 03:25:23 +0200747 .. versionadded:: 3.4.2
748
Guido van Rossumf68afd82016-08-08 09:41:21 -0700749.. method:: AbstractEventLoop.set_debug(enabled: bool)
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100750
751 Set the debug mode of the event loop.
752
Victor Stinner64d750b2014-06-18 03:25:23 +0200753 .. versionadded:: 3.4.2
754
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100755.. seealso::
756
Victor Stinner62511fd2014-06-23 00:36:11 +0200757 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100758
Victor Stinner8c462c52014-01-24 18:11:43 +0100759Server
760------
761
Victor Stinner8ebeb032014-07-11 23:47:40 +0200762.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +0100763
Victor Stinner8ebeb032014-07-11 23:47:40 +0200764 Server listening on sockets.
765
Guido van Rossumf68afd82016-08-08 09:41:21 -0700766 Object created by the :meth:`AbstractEventLoop.create_server` method and the
R David Murray756f0b12015-01-29 19:53:33 -0500767 :func:`start_server` function. Don't instantiate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +0100768
769 .. method:: close()
770
Victor Stinner4bfb14a2014-07-12 03:20:24 +0200771 Stop serving: close listening sockets and set the :attr:`sockets`
772 attribute to ``None``.
773
Berker Peksag49c9edf2016-01-20 07:14:22 +0200774 The sockets that represent existing incoming client connections are left
775 open.
Victor Stinner8ebeb032014-07-11 23:47:40 +0200776
Berker Peksag49c9edf2016-01-20 07:14:22 +0200777 The server is closed asynchronously, use the :meth:`wait_closed`
778 coroutine to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100779
Victor Stinnerbdd574d2015-02-12 22:49:18 +0100780 .. coroutinemethod:: wait_closed()
Victor Stinner8c462c52014-01-24 18:11:43 +0100781
Victor Stinner8ebeb032014-07-11 23:47:40 +0200782 Wait until the :meth:`close` method completes.
783
784 This method is a :ref:`coroutine <coroutine>`.
785
786 .. attribute:: sockets
787
788 List of :class:`socket.socket` objects the server is listening to, or
789 ``None`` if the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100790
791
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500792Handle
793------
794
795.. class:: Handle
796
Guido van Rossumf68afd82016-08-08 09:41:21 -0700797 A callback wrapper object returned by :func:`AbstractEventLoop.call_soon`,
798 :func:`AbstractEventLoop.call_soon_threadsafe`, :func:`AbstractEventLoop.call_later`,
799 and :func:`AbstractEventLoop.call_at`.
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500800
801 .. method:: cancel()
802
Yury Selivanov1096f762015-06-25 13:49:52 -0400803 Cancel the call. If the callback is already canceled or executed,
804 this method has no effect.
Victor Stinneraea82292014-07-08 23:42:38 +0200805
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500806
Victor Stinner6888b962014-10-11 16:15:58 +0200807Event loop examples
Victor Stinnera092a612015-01-09 15:58:41 +0100808-------------------
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500809
Victor Stinner3e09e322013-12-03 01:22:06 +0100810.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100811
Victor Stinner7f314ed2014-10-15 18:49:16 +0200812Hello World with call_soon()
Victor Stinnera092a612015-01-09 15:58:41 +0100813^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinnerea3183f2013-12-03 01:08:00 +0100814
Guido van Rossumf68afd82016-08-08 09:41:21 -0700815Example using the :meth:`AbstractEventLoop.call_soon` method to schedule a
Victor Stinner7f314ed2014-10-15 18:49:16 +0200816callback. The callback displays ``"Hello World"`` and then stops the event
817loop::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100818
819 import asyncio
820
Victor Stinner7f314ed2014-10-15 18:49:16 +0200821 def hello_world(loop):
Victor Stinnerea3183f2013-12-03 01:08:00 +0100822 print('Hello World')
Victor Stinner7f314ed2014-10-15 18:49:16 +0200823 loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100824
825 loop = asyncio.get_event_loop()
Victor Stinner7f314ed2014-10-15 18:49:16 +0200826
827 # Schedule a call to hello_world()
828 loop.call_soon(hello_world, loop)
829
830 # Blocking call interrupted by loop.stop()
831 loop.run_forever()
832 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100833
Victor Stinner3e09e322013-12-03 01:22:06 +0100834.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100835
Victor Stinner6888b962014-10-11 16:15:58 +0200836 The :ref:`Hello World coroutine <asyncio-hello-world-coroutine>` example
837 uses a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100838
Victor Stinner8b863482014-01-27 10:07:50 +0100839
Victor Stinner7f314ed2014-10-15 18:49:16 +0200840.. _asyncio-date-callback:
841
842Display the current date with call_later()
Victor Stinnera092a612015-01-09 15:58:41 +0100843^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner7f314ed2014-10-15 18:49:16 +0200844
845Example of callback displaying the current date every second. The callback uses
Guido van Rossumf68afd82016-08-08 09:41:21 -0700846the :meth:`AbstractEventLoop.call_later` method to reschedule itself during 5
Victor Stinner7f314ed2014-10-15 18:49:16 +0200847seconds, and then stops the event loop::
848
849 import asyncio
850 import datetime
851
852 def display_date(end_time, loop):
853 print(datetime.datetime.now())
854 if (loop.time() + 1.0) < end_time:
855 loop.call_later(1, display_date, end_time, loop)
856 else:
857 loop.stop()
858
859 loop = asyncio.get_event_loop()
860
861 # Schedule the first call to display_date()
862 end_time = loop.time() + 5.0
863 loop.call_soon(display_date, end_time, loop)
864
865 # Blocking call interrupted by loop.stop()
866 loop.run_forever()
867 loop.close()
868
869.. seealso::
870
871 The :ref:`coroutine displaying the current date
872 <asyncio-date-coroutine>` example uses a :ref:`coroutine
873 <coroutine>`.
874
875
Victor Stinner04e6df32014-10-11 16:16:27 +0200876.. _asyncio-watch-read-event:
Victor Stinner8b863482014-01-27 10:07:50 +0100877
Victor Stinner04e6df32014-10-11 16:16:27 +0200878Watch a file descriptor for read events
Victor Stinnera092a612015-01-09 15:58:41 +0100879^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +0200880
881Wait until a file descriptor received some data using the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700882:meth:`AbstractEventLoop.add_reader` method and then close the event loop::
Victor Stinner04e6df32014-10-11 16:16:27 +0200883
884 import asyncio
Victor Stinnerccd8e342014-10-11 16:30:02 +0200885 try:
886 from socket import socketpair
887 except ImportError:
888 from asyncio.windows_utils import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +0200889
890 # Create a pair of connected file descriptors
Victor Stinnerccd8e342014-10-11 16:30:02 +0200891 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200892 loop = asyncio.get_event_loop()
893
894 def reader():
895 data = rsock.recv(100)
896 print("Received:", data.decode())
Victor Stinner2cef3002014-10-23 22:38:46 +0200897 # We are done: unregister the file descriptor
Victor Stinner04e6df32014-10-11 16:16:27 +0200898 loop.remove_reader(rsock)
899 # Stop the event loop
900 loop.stop()
901
Victor Stinner2cef3002014-10-23 22:38:46 +0200902 # Register the file descriptor for read event
Victor Stinner04e6df32014-10-11 16:16:27 +0200903 loop.add_reader(rsock, reader)
904
905 # Simulate the reception of data from the network
906 loop.call_soon(wsock.send, 'abc'.encode())
907
908 # Run the event loop
909 loop.run_forever()
910
911 # We are done, close sockets and the event loop
912 rsock.close()
913 wsock.close()
914 loop.close()
915
916.. seealso::
917
918 The :ref:`register an open socket to wait for data using a protocol
919 <asyncio-register-socket>` example uses a low-level protocol created by the
Guido van Rossumf68afd82016-08-08 09:41:21 -0700920 :meth:`AbstractEventLoop.create_connection` method.
Victor Stinner04e6df32014-10-11 16:16:27 +0200921
922 The :ref:`register an open socket to wait for data using streams
923 <asyncio-register-socket-streams>` example uses high-level streams
924 created by the :func:`open_connection` function in a coroutine.
925
926
927Set signal handlers for SIGINT and SIGTERM
Victor Stinnera092a612015-01-09 15:58:41 +0100928^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Victor Stinner04e6df32014-10-11 16:16:27 +0200929
930Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM` using
Guido van Rossumf68afd82016-08-08 09:41:21 -0700931the :meth:`AbstractEventLoop.add_signal_handler` method::
Victor Stinner8b863482014-01-27 10:07:50 +0100932
933 import asyncio
934 import functools
935 import os
936 import signal
937
938 def ask_exit(signame):
939 print("got signal %s: exit" % signame)
940 loop.stop()
941
942 loop = asyncio.get_event_loop()
943 for signame in ('SIGINT', 'SIGTERM'):
944 loop.add_signal_handler(getattr(signal, signame),
945 functools.partial(ask_exit, signame))
946
Serhiy Storchaka0424eaf2015-09-12 17:45:25 +0300947 print("Event loop running forever, press Ctrl+C to interrupt.")
Victor Stinner8b863482014-01-27 10:07:50 +0100948 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
Victor Stinner63b21a82014-07-05 15:38:59 +0200949 try:
950 loop.run_forever()
951 finally:
952 loop.close()
Victor Stinner2cef3002014-10-23 22:38:46 +0200953
954This example only works on UNIX.