blob: d6c2e30df441b786f5a75b30e396a90f10da8cdf [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`.
9It provides multiple facilities, amongst which:
10
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
Victor Stinneraea82292014-07-08 23:42:38 +020023 Base class of event loops.
Victor Stinnerea3183f2013-12-03 01:08:00 +010024
25Run an event loop
26-----------------
27
28.. method:: BaseEventLoop.run_forever()
29
30 Run until :meth:`stop` is called.
31
32.. method:: BaseEventLoop.run_until_complete(future)
33
Victor Stinner99c2ab42013-12-03 19:17:25 +010034 Run until the :class:`Future` is done.
Victor Stinnerea3183f2013-12-03 01:08:00 +010035
Victor Stinner530ef2f2014-07-08 12:39:10 +020036 If the argument is a :ref:`coroutine object <coroutine>`, it is wrapped by
37 :func:`async`.
Victor Stinnerea3183f2013-12-03 01:08:00 +010038
39 Return the Future's result, or raise its exception.
40
41.. method:: BaseEventLoop.is_running()
42
43 Returns running status of event loop.
44
Victor Stinnerafbf8272013-12-03 02:05:42 +010045.. method:: BaseEventLoop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +010046
47 Stop running the event loop.
48
49 Every callback scheduled before :meth:`stop` is called will run.
Andrew Svetlovca4f3432014-07-24 11:36:33 +030050 Callbacks scheduled after :meth:`stop` is called will not run.
51 However, those callbacks will run if :meth:`run_forever` is called
52 again later.
Victor Stinnerea3183f2013-12-03 01:08:00 +010053
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +020054.. method:: BaseEventLoop.is_closed()
55
56 Returns ``True`` if the event loop was closed.
57
58 .. versionadded:: 3.4.2
59
Victor Stinnerea3183f2013-12-03 01:08:00 +010060.. method:: BaseEventLoop.close()
61
Terry Jan Reedy9ff41802014-07-24 02:59:02 -040062 Close the event loop. The loop must not be running.
Victor Stinnerea3183f2013-12-03 01:08:00 +010063
64 This clears the queues and shuts down the executor, but does not wait for
65 the executor to finish.
66
67 This is idempotent and irreversible. No other methods should be called after
68 this one.
69
Victor Stinner8464c242014-11-28 13:15:41 +010070.. _asyncio-pass-keywords:
Victor Stinnerea3183f2013-12-03 01:08:00 +010071
72Calls
73-----
74
Victor Stinner8464c242014-11-28 13:15:41 +010075Most :mod:`asyncio` functions don't accept keywords. If you want to pass
76keywords to your callback, use :func:`functools.partial`. For example,
77``loop.call_soon(functools.partial(print, "Hello", flush=True))`` will call
78``print("Hello", flush=True)``.
79
80.. note::
81 :func:`functools.partial` is better than ``lambda`` functions, because
82 :mod:`asyncio` can inspect :func:`functools.partial` object to display
83 parameters in debug mode, whereas ``lambda`` functions have a poor
84 representation.
85
Victor Stinnerea3183f2013-12-03 01:08:00 +010086.. method:: BaseEventLoop.call_soon(callback, \*args)
87
88 Arrange for a callback to be called as soon as possible.
89
90 This operates as a FIFO queue, callbacks are called in the order in
91 which they are registered. Each callback will be called exactly once.
92
93 Any positional arguments after the callback will be passed to the
94 callback when it is called.
95
Yury Selivanov43ee1c12014-02-19 20:58:44 -050096 An instance of :class:`asyncio.Handle` is returned.
97
Victor Stinner8464c242014-11-28 13:15:41 +010098 :ref:`Use functools.partial to pass keywords to the callback
99 <asyncio-pass-keywords>`.
100
Victor Stinnerea3183f2013-12-03 01:08:00 +0100101.. method:: BaseEventLoop.call_soon_threadsafe(callback, \*args)
102
103 Like :meth:`call_soon`, but thread safe.
104
105
Victor Stinner45b27ed2014-02-01 02:36:43 +0100106.. _asyncio-delayed-calls:
107
Victor Stinnerea3183f2013-12-03 01:08:00 +0100108Delayed calls
109-------------
110
111The event loop has its own internal clock for computing timeouts.
112Which clock is used depends on the (platform-specific) event loop
113implementation; ideally it is a monotonic clock. This will generally be
114a different clock than :func:`time.time`.
115
Victor Stinnerfd9d3742014-02-18 09:37:43 +0100116.. note::
117
118 Timeouts (relative *delay* or absolute *when*) should not exceed one day.
119
Victor Stinner45b27ed2014-02-01 02:36:43 +0100120
Victor Stinnerea3183f2013-12-03 01:08:00 +0100121.. method:: BaseEventLoop.call_later(delay, callback, *args)
122
123 Arrange for the *callback* to be called after the given *delay*
124 seconds (either an int or float).
125
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500126 An instance of :class:`asyncio.Handle` is returned.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100127
128 *callback* will be called exactly once per call to :meth:`call_later`.
129 If two callbacks are scheduled for exactly the same time, it is
130 undefined which will be called first.
131
132 The optional positional *args* will be passed to the callback when it
133 is called. If you want the callback to be called with some named
134 arguments, use a closure or :func:`functools.partial`.
135
Victor Stinner8464c242014-11-28 13:15:41 +0100136 :ref:`Use functools.partial to pass keywords to the callback
137 <asyncio-pass-keywords>`.
138
Victor Stinnerea3183f2013-12-03 01:08:00 +0100139.. method:: BaseEventLoop.call_at(when, callback, *args)
140
141 Arrange for the *callback* to be called at the given absolute timestamp
Berker Peksagb5563992014-11-07 19:51:07 +0200142 *when* (an int or float), using the same time reference as
143 :meth:`BaseEventLoop.time`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100144
145 This method's behavior is the same as :meth:`call_later`.
146
Victor Stinner8464c242014-11-28 13:15:41 +0100147 :ref:`Use functools.partial to pass keywords to the callback
148 <asyncio-pass-keywords>`.
149
Victor Stinnerea3183f2013-12-03 01:08:00 +0100150.. method:: BaseEventLoop.time()
151
152 Return the current time, as a :class:`float` value, according to the
153 event loop's internal clock.
154
Victor Stinner3e09e322013-12-03 01:22:06 +0100155.. seealso::
156
157 The :func:`asyncio.sleep` function.
158
Victor Stinnerea3183f2013-12-03 01:08:00 +0100159
Victor Stinner530ef2f2014-07-08 12:39:10 +0200160Coroutines
161----------
162
163.. method:: BaseEventLoop.create_task(coro)
164
165 Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in
166 a future. Return a :class:`Task` object.
167
168 Third-party event loops can use their own subclass of :class:`Task` for
169 interoperability. In this case, the result type is a subclass of
170 :class:`Task`.
171
Victor Stinner337e03f2014-08-11 01:11:13 +0200172 This method was added in Python 3.4.2. Use the :func:`async` function to
173 support also older Python versions.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200174
175 .. versionadded:: 3.4.2
176
177
Victor Stinnerea3183f2013-12-03 01:08:00 +0100178Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100179--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100180
181.. method:: BaseEventLoop.create_connection(protocol_factory, host=None, port=None, \*, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None)
182
183 Create a streaming transport connection to a given Internet *host* and
Victor Stinnera6919aa2014-02-19 13:32:34 +0100184 *port*: socket family :py:data:`~socket.AF_INET` or
185 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
186 socket type :py:data:`~socket.SOCK_STREAM`. *protocol_factory* must be a
187 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100188
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500189 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100190 establish the connection in the background. When successful, the
191 coroutine returns a ``(transport, protocol)`` pair.
192
193 The chronological synopsis of the underlying operation is as follows:
194
Victor Stinner9592edb2014-02-02 15:03:02 +0100195 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100196 is created to represent it.
197
198 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100199 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100200
201 #. The protocol instance is tied to the transport, and its
202 :meth:`connection_made` method is called.
203
204 #. The coroutine returns successfully with the ``(transport, protocol)``
205 pair.
206
207 The created transport is an implementation-dependent bidirectional stream.
208
209 .. note::
210 *protocol_factory* can be any kind of callable, not necessarily
211 a class. For example, if you want to use a pre-created
212 protocol instance, you can pass ``lambda: my_protocol``.
213
214 Options allowing to change how the connection is created:
215
216 * *ssl*: if given and not false, a SSL/TLS transport is created
217 (by default a plain TCP transport is created). If *ssl* is
218 a :class:`ssl.SSLContext` object, this context is used to create
219 the transport; if *ssl* is :const:`True`, a context with some
220 unspecified default settings is used.
221
Berker Peksag9c1dba22014-09-28 00:00:58 +0300222 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100223
Victor Stinnerea3183f2013-12-03 01:08:00 +0100224 * *server_hostname*, is only for use together with *ssl*,
225 and sets or overrides the hostname that the target server's certificate
226 will be matched against. By default the value of the *host* argument
227 is used. If *host* is empty, there is no default and you must pass a
228 value for *server_hostname*. If *server_hostname* is an empty
229 string, hostname matching is disabled (which is a serious security
230 risk, allowing for man-in-the-middle-attacks).
231
232 * *family*, *proto*, *flags* are the optional address family, protocol
233 and flags to be passed through to getaddrinfo() for *host* resolution.
234 If given, these should all be integers from the corresponding
235 :mod:`socket` module constants.
236
237 * *sock*, if given, should be an existing, already connected
238 :class:`socket.socket` object to be used by the transport.
239 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
240 and *local_addr* should be specified.
241
242 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
243 to bind the socket to locally. The *local_host* and *local_port*
244 are looked up using getaddrinfo(), similarly to *host* and *port*.
245
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200246 On Windows with :class:`ProactorEventLoop`, SSL/TLS is not supported.
247
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100248 .. seealso::
249
250 The :func:`open_connection` function can be used to get a pair of
251 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
252
Victor Stinnerea3183f2013-12-03 01:08:00 +0100253
Victor Stinnera6919aa2014-02-19 13:32:34 +0100254.. method:: BaseEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0)
255
256 Create datagram connection: socket family :py:data:`~socket.AF_INET` or
257 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
258 socket type :py:data:`~socket.SOCK_DGRAM`.
259
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500260 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100261 establish the connection in the background. When successful, the
262 coroutine returns a ``(transport, protocol)`` pair.
263
264 See the :meth:`BaseEventLoop.create_connection` method for parameters.
265
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200266 On Windows with :class:`ProactorEventLoop`, this method is not supported.
267
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200268 See :ref:`UDP echo client protocol <asyncio-udp-echo-client-protocol>` and
269 :ref:`UDP echo server protocol <asyncio-udp-echo-server-protocol>` examples.
270
Victor Stinnera6919aa2014-02-19 13:32:34 +0100271
272.. method:: BaseEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
273
274 Create UNIX connection: socket family :py:data:`~socket.AF_UNIX`, socket
275 type :py:data:`~socket.SOCK_STREAM`. The :py:data:`~socket.AF_UNIX` socket
276 family is used to communicate between processes on the same machine
277 efficiently.
278
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500279 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100280 establish the connection in the background. When successful, the
281 coroutine returns a ``(transport, protocol)`` pair.
282
283 See the :meth:`BaseEventLoop.create_connection` method for parameters.
284
285 Availability: UNIX.
286
287
Victor Stinnerea3183f2013-12-03 01:08:00 +0100288Creating listening connections
289------------------------------
290
291.. method:: BaseEventLoop.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)
292
Victor Stinner33f6abe2014-10-12 20:36:04 +0200293 Create a TCP server (socket type :data:`~socket.SOCK_STREAM`) bound to
294 *host* and *port*.
295
296 Return a :class:`Server` object, its :attr:`~Server.sockets` attribute
297 contains created sockets. Use the :meth:`Server.close` method to stop the
298 server: close listening sockets.
299
300 Parameters:
301
302 * If *host* is an empty string or ``None``, all interfaces are assumed
303 and a list of multiple sockets will be returned (most likely
304 one for IPv4 and another one for IPv6).
305
306 * *family* can be set to either :data:`socket.AF_INET` or
307 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
308 it will be determined from host (defaults to :data:`socket.AF_UNSPEC`).
309
310 * *flags* is a bitmask for :meth:`getaddrinfo`.
311
312 * *sock* can optionally be specified in order to use a preexisting
313 socket object. If specified, *host* and *port* should be omitted (must be
314 :const:`None`).
315
316 * *backlog* is the maximum number of queued connections passed to
317 :meth:`~socket.socket.listen` (defaults to 100).
318
319 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the
320 accepted connections.
321
322 * *reuse_address* tells the kernel to reuse a local socket in
323 TIME_WAIT state, without waiting for its natural timeout to
324 expire. If not specified will automatically be set to True on
325 UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100326
Victor Stinnerd1432092014-06-19 17:11:49 +0200327 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100328
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200329 On Windows with :class:`ProactorEventLoop`, SSL/TLS is not supported.
330
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100331 .. seealso::
332
333 The function :func:`start_server` creates a (:class:`StreamReader`,
334 :class:`StreamWriter`) pair and calls back a function with this pair.
335
Victor Stinnerea3183f2013-12-03 01:08:00 +0100336
Victor Stinnera6919aa2014-02-19 13:32:34 +0100337.. method:: BaseEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100338
Victor Stinnera6919aa2014-02-19 13:32:34 +0100339 Similar to :meth:`BaseEventLoop.create_server`, but specific to the
340 socket family :py:data:`~socket.AF_UNIX`.
341
342 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100343
344
Victor Stinnerc1567df2014-02-08 23:22:58 +0100345Watch file descriptors
346----------------------
347
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200348On Windows with :class:`SelectorEventLoop`, only socket handles are supported
349(ex: pipe file descriptors are not supported).
350
351On Windows with :class:`ProactorEventLoop`, these methods are not supported.
352
Victor Stinnerc1567df2014-02-08 23:22:58 +0100353.. method:: BaseEventLoop.add_reader(fd, callback, \*args)
354
355 Start watching the file descriptor for read availability and then call the
356 *callback* with specified arguments.
357
Victor Stinner8464c242014-11-28 13:15:41 +0100358 :ref:`Use functools.partial to pass keywords to the callback
359 <asyncio-pass-keywords>`.
360
Victor Stinnerc1567df2014-02-08 23:22:58 +0100361.. method:: BaseEventLoop.remove_reader(fd)
362
363 Stop watching the file descriptor for read availability.
364
365.. method:: BaseEventLoop.add_writer(fd, callback, \*args)
366
367 Start watching the file descriptor for write availability and then call the
368 *callback* with specified arguments.
369
Victor Stinner8464c242014-11-28 13:15:41 +0100370 :ref:`Use functools.partial to pass keywords to the callback
371 <asyncio-pass-keywords>`.
372
Victor Stinnerc1567df2014-02-08 23:22:58 +0100373.. method:: BaseEventLoop.remove_writer(fd)
374
375 Stop watching the file descriptor for write availability.
376
Victor Stinner04e6df32014-10-11 16:16:27 +0200377The :ref:`watch a file descriptor for read events <asyncio-watch-read-event>`
378example uses the low-level :meth:`BaseEventLoop.add_reader` method to register
379the file descriptor of a socket.
380
Victor Stinnerc1567df2014-02-08 23:22:58 +0100381
382Low-level socket operations
383---------------------------
384
385.. method:: BaseEventLoop.sock_recv(sock, nbytes)
386
387 Receive data from the socket. The return value is a bytes object
388 representing the data received. The maximum amount of data to be received
389 at once is specified by *nbytes*.
390
Victor Stinnerd84fd732014-08-26 01:01:59 +0200391 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
392 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200393
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500394 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100395
396 .. seealso::
397
398 The :meth:`socket.socket.recv` method.
399
400.. method:: BaseEventLoop.sock_sendall(sock, data)
401
402 Send data to the socket. The socket must be connected to a remote socket.
403 This method continues to send data from *data* until either all data has
404 been sent or an error occurs. ``None`` is returned on success. On error,
405 an exception is raised, and there is no way to determine how much data, if
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500406 any, was successfully processed by the receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100407
Victor Stinnerd84fd732014-08-26 01:01:59 +0200408 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
409 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200410
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500411 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100412
413 .. seealso::
414
415 The :meth:`socket.socket.sendall` method.
416
417.. method:: BaseEventLoop.sock_connect(sock, address)
418
419 Connect to a remote socket at *address*.
420
Victor Stinner1b0580b2014-02-13 09:24:37 +0100421 The *address* must be already resolved to avoid the trap of hanging the
422 entire event loop when the address requires doing a DNS lookup. For
423 example, it must be an IP address, not an hostname, for
424 :py:data:`~socket.AF_INET` and :py:data:`~socket.AF_INET6` address families.
425 Use :meth:`getaddrinfo` to resolve the hostname asynchronously.
426
Victor Stinnerd84fd732014-08-26 01:01:59 +0200427 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
428 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200429
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500430 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100431
432 .. seealso::
433
434 The :meth:`BaseEventLoop.create_connection` method, the
435 :func:`open_connection` function and the :meth:`socket.socket.connect`
436 method.
437
438
439.. method:: BaseEventLoop.sock_accept(sock)
440
441 Accept a connection. The socket must be bound to an address and listening
442 for connections. The return value is a pair ``(conn, address)`` where *conn*
443 is a *new* socket object usable to send and receive data on the connection,
444 and *address* is the address bound to the socket on the other end of the
445 connection.
446
Victor Stinnerec2ce092014-07-29 23:12:22 +0200447 The socket *sock* must be non-blocking.
448
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500449 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100450
451 .. seealso::
452
453 The :meth:`BaseEventLoop.create_server` method, the :func:`start_server`
454 function and the :meth:`socket.socket.accept` method.
455
456
457Resolve host name
458-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100459
460.. method:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
461
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500462 This method is a :ref:`coroutine <coroutine>`, similar to
463 :meth:`socket.getaddrinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100464
465.. method:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
466
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500467 This method is a :ref:`coroutine <coroutine>`, similar to
468 :meth:`socket.getnameinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100469
470
Victor Stinner984600f2014-03-25 09:40:26 +0100471Connect pipes
472-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100473
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200474On Windows with :class:`SelectorEventLoop`, these methods are not supported.
475Use :class:`ProactorEventLoop` to support pipes on Windows.
476
Victor Stinnerea3183f2013-12-03 01:08:00 +0100477.. method:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
478
Victor Stinnerd84fd732014-08-26 01:01:59 +0200479 Register read pipe in eventloop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100480
481 *protocol_factory* should instantiate object with :class:`Protocol`
Victor Stinnera5b257a2014-05-29 00:14:03 +0200482 interface. *pipe* is a :term:`file-like object <file object>`.
483 Return pair ``(transport, protocol)``, where *transport* supports the
Victor Stinnerea3183f2013-12-03 01:08:00 +0100484 :class:`ReadTransport` interface.
485
Victor Stinnerd84fd732014-08-26 01:01:59 +0200486 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
487 non-blocking mode.
488
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500489 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100490
491.. method:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
492
493 Register write pipe in eventloop.
494
495 *protocol_factory* should instantiate object with :class:`BaseProtocol`
Victor Stinner2cef3002014-10-23 22:38:46 +0200496 interface. *pipe* is :term:`file-like object <file object>`.
497 Return pair ``(transport, protocol)``, where *transport* supports
Victor Stinnerea3183f2013-12-03 01:08:00 +0100498 :class:`WriteTransport` interface.
499
Victor Stinnerd84fd732014-08-26 01:01:59 +0200500 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
501 non-blocking mode.
502
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500503 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100504
Victor Stinner08444382014-02-02 22:43:39 +0100505.. seealso::
506
Victor Stinner984600f2014-03-25 09:40:26 +0100507 The :meth:`BaseEventLoop.subprocess_exec` and
508 :meth:`BaseEventLoop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100509
Victor Stinnerea3183f2013-12-03 01:08:00 +0100510
Victor Stinner8b863482014-01-27 10:07:50 +0100511UNIX signals
512------------
513
514Availability: UNIX only.
515
516.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
517
518 Add a handler for a signal.
519
520 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
521 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
522
Victor Stinner8464c242014-11-28 13:15:41 +0100523 :ref:`Use functools.partial to pass keywords to the callback
524 <asyncio-pass-keywords>`.
525
Victor Stinner8b863482014-01-27 10:07:50 +0100526.. method:: BaseEventLoop.remove_signal_handler(sig)
527
528 Remove a handler for a signal.
529
530 Return ``True`` if a signal handler was removed, ``False`` if not.
531
532.. seealso::
533
534 The :mod:`signal` module.
535
536
Victor Stinnerea3183f2013-12-03 01:08:00 +0100537Executor
538--------
539
540Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
541pool of processes). By default, an event loop uses a thread pool executor
542(:class:`~concurrent.futures.ThreadPoolExecutor`).
543
544.. method:: BaseEventLoop.run_in_executor(executor, callback, \*args)
545
546 Arrange for a callback to be called in the specified executor.
547
Larry Hastings3732ed22014-03-15 21:13:56 -0700548 The *executor* argument should be an :class:`~concurrent.futures.Executor`
549 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100550
Victor Stinner8464c242014-11-28 13:15:41 +0100551 :ref:`Use functools.partial to pass keywords to the callback
552 <asyncio-pass-keywords>`.
553
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500554 This method is a :ref:`coroutine <coroutine>`.
555
Victor Stinnerea3183f2013-12-03 01:08:00 +0100556.. method:: BaseEventLoop.set_default_executor(executor)
557
558 Set the default executor used by :meth:`run_in_executor`.
559
560
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500561Error Handling API
562------------------
563
564Allows to customize how exceptions are handled in the event loop.
565
566.. method:: BaseEventLoop.set_exception_handler(handler)
567
568 Set *handler* as the new event loop exception handler.
569
570 If *handler* is ``None``, the default exception handler will
571 be set.
572
573 If *handler* is a callable object, it should have a
574 matching signature to ``(loop, context)``, where ``loop``
575 will be a reference to the active event loop, ``context``
576 will be a ``dict`` object (see :meth:`call_exception_handler`
577 documentation for details about context).
578
579.. method:: BaseEventLoop.default_exception_handler(context)
580
581 Default exception handler.
582
583 This is called when an exception occurs and no exception
584 handler is set, and can be called by a custom exception
585 handler that wants to defer to the default behavior.
586
587 *context* parameter has the same meaning as in
588 :meth:`call_exception_handler`.
589
590.. method:: BaseEventLoop.call_exception_handler(context)
591
592 Call the current event loop exception handler.
593
594 *context* is a ``dict`` object containing the following keys
595 (new keys may be introduced later):
596
597 * 'message': Error message;
598 * 'exception' (optional): Exception object;
599 * 'future' (optional): :class:`asyncio.Future` instance;
600 * 'handle' (optional): :class:`asyncio.Handle` instance;
601 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
602 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
603 * 'socket' (optional): :class:`socket.socket` instance.
604
605 .. note::
606
607 Note: this method should not be overloaded in subclassed
608 event loops. For any custom exception handling, use
609 :meth:`set_exception_handler()` method.
610
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100611Debug mode
612----------
613
614.. method:: BaseEventLoop.get_debug()
615
Victor Stinner7b7120e2014-06-23 00:12:14 +0200616 Get the debug mode (:class:`bool`) of the event loop.
617
618 The default value is ``True`` if the environment variable
619 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
620 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100621
Victor Stinner64d750b2014-06-18 03:25:23 +0200622 .. versionadded:: 3.4.2
623
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100624.. method:: BaseEventLoop.set_debug(enabled: bool)
625
626 Set the debug mode of the event loop.
627
Victor Stinner64d750b2014-06-18 03:25:23 +0200628 .. versionadded:: 3.4.2
629
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100630.. seealso::
631
Victor Stinner62511fd2014-06-23 00:36:11 +0200632 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100633
Victor Stinner8c462c52014-01-24 18:11:43 +0100634Server
635------
636
Victor Stinner8ebeb032014-07-11 23:47:40 +0200637.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +0100638
Victor Stinner8ebeb032014-07-11 23:47:40 +0200639 Server listening on sockets.
640
641 Object created by the :meth:`BaseEventLoop.create_server` method and the
642 :func:`start_server` function. Don't instanciate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +0100643
644 .. method:: close()
645
Victor Stinner4bfb14a2014-07-12 03:20:24 +0200646 Stop serving: close listening sockets and set the :attr:`sockets`
647 attribute to ``None``.
648
649 The sockets that represent existing incoming client connections are
650 leaved open.
Victor Stinner8ebeb032014-07-11 23:47:40 +0200651
652 The server is closed asynchonously, use the :meth:`wait_closed` coroutine
653 to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100654
655 .. method:: wait_closed()
656
Victor Stinner8ebeb032014-07-11 23:47:40 +0200657 Wait until the :meth:`close` method completes.
658
659 This method is a :ref:`coroutine <coroutine>`.
660
661 .. attribute:: sockets
662
663 List of :class:`socket.socket` objects the server is listening to, or
664 ``None`` if the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100665
666
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500667Handle
668------
669
670.. class:: Handle
671
672 A callback wrapper object returned by :func:`BaseEventLoop.call_soon`,
673 :func:`BaseEventLoop.call_soon_threadsafe`, :func:`BaseEventLoop.call_later`,
674 and :func:`BaseEventLoop.call_at`.
675
676 .. method:: cancel()
677
Victor Stinneraea82292014-07-08 23:42:38 +0200678 Cancel the call.
679
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500680
Victor Stinner6888b962014-10-11 16:15:58 +0200681Event loop examples
682===================
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500683
Victor Stinner3e09e322013-12-03 01:22:06 +0100684.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100685
Victor Stinner7f314ed2014-10-15 18:49:16 +0200686Hello World with call_soon()
687----------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100688
Victor Stinner7f314ed2014-10-15 18:49:16 +0200689Example using the :meth:`BaseEventLoop.call_soon` method to schedule a
690callback. The callback displays ``"Hello World"`` and then stops the event
691loop::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100692
693 import asyncio
694
Victor Stinner7f314ed2014-10-15 18:49:16 +0200695 def hello_world(loop):
Victor Stinnerea3183f2013-12-03 01:08:00 +0100696 print('Hello World')
Victor Stinner7f314ed2014-10-15 18:49:16 +0200697 loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100698
699 loop = asyncio.get_event_loop()
Victor Stinner7f314ed2014-10-15 18:49:16 +0200700
701 # Schedule a call to hello_world()
702 loop.call_soon(hello_world, loop)
703
704 # Blocking call interrupted by loop.stop()
705 loop.run_forever()
706 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100707
Victor Stinner3e09e322013-12-03 01:22:06 +0100708.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100709
Victor Stinner6888b962014-10-11 16:15:58 +0200710 The :ref:`Hello World coroutine <asyncio-hello-world-coroutine>` example
711 uses a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100712
Victor Stinner8b863482014-01-27 10:07:50 +0100713
Victor Stinner7f314ed2014-10-15 18:49:16 +0200714.. _asyncio-date-callback:
715
716Display the current date with call_later()
717------------------------------------------
718
719Example of callback displaying the current date every second. The callback uses
720the :meth:`BaseEventLoop.call_later` method to reschedule itself during 5
721seconds, and then stops the event loop::
722
723 import asyncio
724 import datetime
725
726 def display_date(end_time, loop):
727 print(datetime.datetime.now())
728 if (loop.time() + 1.0) < end_time:
729 loop.call_later(1, display_date, end_time, loop)
730 else:
731 loop.stop()
732
733 loop = asyncio.get_event_loop()
734
735 # Schedule the first call to display_date()
736 end_time = loop.time() + 5.0
737 loop.call_soon(display_date, end_time, loop)
738
739 # Blocking call interrupted by loop.stop()
740 loop.run_forever()
741 loop.close()
742
743.. seealso::
744
745 The :ref:`coroutine displaying the current date
746 <asyncio-date-coroutine>` example uses a :ref:`coroutine
747 <coroutine>`.
748
749
Victor Stinner04e6df32014-10-11 16:16:27 +0200750.. _asyncio-watch-read-event:
Victor Stinner8b863482014-01-27 10:07:50 +0100751
Victor Stinner04e6df32014-10-11 16:16:27 +0200752Watch a file descriptor for read events
753---------------------------------------
754
755Wait until a file descriptor received some data using the
756:meth:`BaseEventLoop.add_reader` method and then close the event loop::
757
758 import asyncio
Victor Stinnerccd8e342014-10-11 16:30:02 +0200759 try:
760 from socket import socketpair
761 except ImportError:
762 from asyncio.windows_utils import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +0200763
764 # Create a pair of connected file descriptors
Victor Stinnerccd8e342014-10-11 16:30:02 +0200765 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200766 loop = asyncio.get_event_loop()
767
768 def reader():
769 data = rsock.recv(100)
770 print("Received:", data.decode())
Victor Stinner2cef3002014-10-23 22:38:46 +0200771 # We are done: unregister the file descriptor
Victor Stinner04e6df32014-10-11 16:16:27 +0200772 loop.remove_reader(rsock)
773 # Stop the event loop
774 loop.stop()
775
Victor Stinner2cef3002014-10-23 22:38:46 +0200776 # Register the file descriptor for read event
Victor Stinner04e6df32014-10-11 16:16:27 +0200777 loop.add_reader(rsock, reader)
778
779 # Simulate the reception of data from the network
780 loop.call_soon(wsock.send, 'abc'.encode())
781
782 # Run the event loop
783 loop.run_forever()
784
785 # We are done, close sockets and the event loop
786 rsock.close()
787 wsock.close()
788 loop.close()
789
790.. seealso::
791
792 The :ref:`register an open socket to wait for data using a protocol
793 <asyncio-register-socket>` example uses a low-level protocol created by the
794 :meth:`BaseEventLoop.create_connection` method.
795
796 The :ref:`register an open socket to wait for data using streams
797 <asyncio-register-socket-streams>` example uses high-level streams
798 created by the :func:`open_connection` function in a coroutine.
799
800
801Set signal handlers for SIGINT and SIGTERM
802------------------------------------------
803
804Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM` using
805the :meth:`BaseEventLoop.add_signal_handler` method::
Victor Stinner8b863482014-01-27 10:07:50 +0100806
807 import asyncio
808 import functools
809 import os
810 import signal
811
812 def ask_exit(signame):
813 print("got signal %s: exit" % signame)
814 loop.stop()
815
816 loop = asyncio.get_event_loop()
817 for signame in ('SIGINT', 'SIGTERM'):
818 loop.add_signal_handler(getattr(signal, signame),
819 functools.partial(ask_exit, signame))
820
821 print("Event loop running forever, press CTRL+c to interrupt.")
822 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
Victor Stinner63b21a82014-07-05 15:38:59 +0200823 try:
824 loop.run_forever()
825 finally:
826 loop.close()
Victor Stinner2cef3002014-10-23 22:38:46 +0200827
828This example only works on UNIX.