blob: ec884759ce725eece40262a11f094cd378f59744 [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
70
71Calls
72-----
73
74.. method:: BaseEventLoop.call_soon(callback, \*args)
75
76 Arrange for a callback to be called as soon as possible.
77
78 This operates as a FIFO queue, callbacks are called in the order in
79 which they are registered. Each callback will be called exactly once.
80
81 Any positional arguments after the callback will be passed to the
82 callback when it is called.
83
Yury Selivanov43ee1c12014-02-19 20:58:44 -050084 An instance of :class:`asyncio.Handle` is returned.
85
Victor Stinnerea3183f2013-12-03 01:08:00 +010086.. method:: BaseEventLoop.call_soon_threadsafe(callback, \*args)
87
88 Like :meth:`call_soon`, but thread safe.
89
90
Victor Stinner45b27ed2014-02-01 02:36:43 +010091.. _asyncio-delayed-calls:
92
Victor Stinnerea3183f2013-12-03 01:08:00 +010093Delayed calls
94-------------
95
96The event loop has its own internal clock for computing timeouts.
97Which clock is used depends on the (platform-specific) event loop
98implementation; ideally it is a monotonic clock. This will generally be
99a different clock than :func:`time.time`.
100
Victor Stinnerfd9d3742014-02-18 09:37:43 +0100101.. note::
102
103 Timeouts (relative *delay* or absolute *when*) should not exceed one day.
104
Victor Stinner45b27ed2014-02-01 02:36:43 +0100105
Victor Stinnerea3183f2013-12-03 01:08:00 +0100106.. method:: BaseEventLoop.call_later(delay, callback, *args)
107
108 Arrange for the *callback* to be called after the given *delay*
109 seconds (either an int or float).
110
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500111 An instance of :class:`asyncio.Handle` is returned.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100112
113 *callback* will be called exactly once per call to :meth:`call_later`.
114 If two callbacks are scheduled for exactly the same time, it is
115 undefined which will be called first.
116
117 The optional positional *args* will be passed to the callback when it
118 is called. If you want the callback to be called with some named
119 arguments, use a closure or :func:`functools.partial`.
120
121.. method:: BaseEventLoop.call_at(when, callback, *args)
122
123 Arrange for the *callback* to be called at the given absolute timestamp
124 *when* (an int or float), using the same time reference as :meth:`time`.
125
126 This method's behavior is the same as :meth:`call_later`.
127
128.. method:: BaseEventLoop.time()
129
130 Return the current time, as a :class:`float` value, according to the
131 event loop's internal clock.
132
Victor Stinner3e09e322013-12-03 01:22:06 +0100133.. seealso::
134
135 The :func:`asyncio.sleep` function.
136
Victor Stinnerea3183f2013-12-03 01:08:00 +0100137
Victor Stinner530ef2f2014-07-08 12:39:10 +0200138Coroutines
139----------
140
141.. method:: BaseEventLoop.create_task(coro)
142
143 Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in
144 a future. Return a :class:`Task` object.
145
146 Third-party event loops can use their own subclass of :class:`Task` for
147 interoperability. In this case, the result type is a subclass of
148 :class:`Task`.
149
Victor Stinner337e03f2014-08-11 01:11:13 +0200150 This method was added in Python 3.4.2. Use the :func:`async` function to
151 support also older Python versions.
Victor Stinner530ef2f2014-07-08 12:39:10 +0200152
153 .. versionadded:: 3.4.2
154
155
Victor Stinnerea3183f2013-12-03 01:08:00 +0100156Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100157--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100158
159.. 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)
160
161 Create a streaming transport connection to a given Internet *host* and
Victor Stinnera6919aa2014-02-19 13:32:34 +0100162 *port*: socket family :py:data:`~socket.AF_INET` or
163 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
164 socket type :py:data:`~socket.SOCK_STREAM`. *protocol_factory* must be a
165 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100166
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500167 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100168 establish the connection in the background. When successful, the
169 coroutine returns a ``(transport, protocol)`` pair.
170
171 The chronological synopsis of the underlying operation is as follows:
172
Victor Stinner9592edb2014-02-02 15:03:02 +0100173 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100174 is created to represent it.
175
176 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100177 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100178
179 #. The protocol instance is tied to the transport, and its
180 :meth:`connection_made` method is called.
181
182 #. The coroutine returns successfully with the ``(transport, protocol)``
183 pair.
184
185 The created transport is an implementation-dependent bidirectional stream.
186
187 .. note::
188 *protocol_factory* can be any kind of callable, not necessarily
189 a class. For example, if you want to use a pre-created
190 protocol instance, you can pass ``lambda: my_protocol``.
191
192 Options allowing to change how the connection is created:
193
194 * *ssl*: if given and not false, a SSL/TLS transport is created
195 (by default a plain TCP transport is created). If *ssl* is
196 a :class:`ssl.SSLContext` object, this context is used to create
197 the transport; if *ssl* is :const:`True`, a context with some
198 unspecified default settings is used.
199
Berker Peksag9c1dba22014-09-28 00:00:58 +0300200 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100201
Victor Stinnerea3183f2013-12-03 01:08:00 +0100202 * *server_hostname*, is only for use together with *ssl*,
203 and sets or overrides the hostname that the target server's certificate
204 will be matched against. By default the value of the *host* argument
205 is used. If *host* is empty, there is no default and you must pass a
206 value for *server_hostname*. If *server_hostname* is an empty
207 string, hostname matching is disabled (which is a serious security
208 risk, allowing for man-in-the-middle-attacks).
209
210 * *family*, *proto*, *flags* are the optional address family, protocol
211 and flags to be passed through to getaddrinfo() for *host* resolution.
212 If given, these should all be integers from the corresponding
213 :mod:`socket` module constants.
214
215 * *sock*, if given, should be an existing, already connected
216 :class:`socket.socket` object to be used by the transport.
217 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
218 and *local_addr* should be specified.
219
220 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
221 to bind the socket to locally. The *local_host* and *local_port*
222 are looked up using getaddrinfo(), similarly to *host* and *port*.
223
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200224 On Windows with :class:`ProactorEventLoop`, SSL/TLS is not supported.
225
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100226 .. seealso::
227
228 The :func:`open_connection` function can be used to get a pair of
229 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
230
Victor Stinnerea3183f2013-12-03 01:08:00 +0100231
Victor Stinnera6919aa2014-02-19 13:32:34 +0100232.. method:: BaseEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0)
233
234 Create datagram connection: socket family :py:data:`~socket.AF_INET` or
235 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
236 socket type :py:data:`~socket.SOCK_DGRAM`.
237
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500238 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100239 establish the connection in the background. When successful, the
240 coroutine returns a ``(transport, protocol)`` pair.
241
242 See the :meth:`BaseEventLoop.create_connection` method for parameters.
243
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200244 On Windows with :class:`ProactorEventLoop`, this method is not supported.
245
Victor Stinnerc7edffd2014-10-12 11:24:26 +0200246 See :ref:`UDP echo client protocol <asyncio-udp-echo-client-protocol>` and
247 :ref:`UDP echo server protocol <asyncio-udp-echo-server-protocol>` examples.
248
Victor Stinnera6919aa2014-02-19 13:32:34 +0100249
250.. method:: BaseEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
251
252 Create UNIX connection: socket family :py:data:`~socket.AF_UNIX`, socket
253 type :py:data:`~socket.SOCK_STREAM`. The :py:data:`~socket.AF_UNIX` socket
254 family is used to communicate between processes on the same machine
255 efficiently.
256
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500257 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100258 establish the connection in the background. When successful, the
259 coroutine returns a ``(transport, protocol)`` pair.
260
261 See the :meth:`BaseEventLoop.create_connection` method for parameters.
262
263 Availability: UNIX.
264
265
Victor Stinnerea3183f2013-12-03 01:08:00 +0100266Creating listening connections
267------------------------------
268
269.. 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)
270
Victor Stinner33f6abe2014-10-12 20:36:04 +0200271 Create a TCP server (socket type :data:`~socket.SOCK_STREAM`) bound to
272 *host* and *port*.
273
274 Return a :class:`Server` object, its :attr:`~Server.sockets` attribute
275 contains created sockets. Use the :meth:`Server.close` method to stop the
276 server: close listening sockets.
277
278 Parameters:
279
280 * If *host* is an empty string or ``None``, all interfaces are assumed
281 and a list of multiple sockets will be returned (most likely
282 one for IPv4 and another one for IPv6).
283
284 * *family* can be set to either :data:`socket.AF_INET` or
285 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
286 it will be determined from host (defaults to :data:`socket.AF_UNSPEC`).
287
288 * *flags* is a bitmask for :meth:`getaddrinfo`.
289
290 * *sock* can optionally be specified in order to use a preexisting
291 socket object. If specified, *host* and *port* should be omitted (must be
292 :const:`None`).
293
294 * *backlog* is the maximum number of queued connections passed to
295 :meth:`~socket.socket.listen` (defaults to 100).
296
297 * *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the
298 accepted connections.
299
300 * *reuse_address* tells the kernel to reuse a local socket in
301 TIME_WAIT state, without waiting for its natural timeout to
302 expire. If not specified will automatically be set to True on
303 UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100304
Victor Stinnerd1432092014-06-19 17:11:49 +0200305 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100306
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200307 On Windows with :class:`ProactorEventLoop`, SSL/TLS is not supported.
308
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100309 .. seealso::
310
311 The function :func:`start_server` creates a (:class:`StreamReader`,
312 :class:`StreamWriter`) pair and calls back a function with this pair.
313
Victor Stinnerea3183f2013-12-03 01:08:00 +0100314
Victor Stinnera6919aa2014-02-19 13:32:34 +0100315.. method:: BaseEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100316
Victor Stinnera6919aa2014-02-19 13:32:34 +0100317 Similar to :meth:`BaseEventLoop.create_server`, but specific to the
318 socket family :py:data:`~socket.AF_UNIX`.
319
320 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100321
322
Victor Stinnerc1567df2014-02-08 23:22:58 +0100323Watch file descriptors
324----------------------
325
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200326On Windows with :class:`SelectorEventLoop`, only socket handles are supported
327(ex: pipe file descriptors are not supported).
328
329On Windows with :class:`ProactorEventLoop`, these methods are not supported.
330
Victor Stinnerc1567df2014-02-08 23:22:58 +0100331.. method:: BaseEventLoop.add_reader(fd, callback, \*args)
332
333 Start watching the file descriptor for read availability and then call the
334 *callback* with specified arguments.
335
336.. method:: BaseEventLoop.remove_reader(fd)
337
338 Stop watching the file descriptor for read availability.
339
340.. method:: BaseEventLoop.add_writer(fd, callback, \*args)
341
342 Start watching the file descriptor for write availability and then call the
343 *callback* with specified arguments.
344
345.. method:: BaseEventLoop.remove_writer(fd)
346
347 Stop watching the file descriptor for write availability.
348
Victor Stinner04e6df32014-10-11 16:16:27 +0200349The :ref:`watch a file descriptor for read events <asyncio-watch-read-event>`
350example uses the low-level :meth:`BaseEventLoop.add_reader` method to register
351the file descriptor of a socket.
352
Victor Stinnerc1567df2014-02-08 23:22:58 +0100353
354Low-level socket operations
355---------------------------
356
357.. method:: BaseEventLoop.sock_recv(sock, nbytes)
358
359 Receive data from the socket. The return value is a bytes object
360 representing the data received. The maximum amount of data to be received
361 at once is specified by *nbytes*.
362
Victor Stinnerd84fd732014-08-26 01:01:59 +0200363 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
364 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200365
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500366 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100367
368 .. seealso::
369
370 The :meth:`socket.socket.recv` method.
371
372.. method:: BaseEventLoop.sock_sendall(sock, data)
373
374 Send data to the socket. The socket must be connected to a remote socket.
375 This method continues to send data from *data* until either all data has
376 been sent or an error occurs. ``None`` is returned on success. On error,
377 an exception is raised, and there is no way to determine how much data, if
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500378 any, was successfully processed by the receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100379
Victor Stinnerd84fd732014-08-26 01:01:59 +0200380 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
381 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200382
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500383 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100384
385 .. seealso::
386
387 The :meth:`socket.socket.sendall` method.
388
389.. method:: BaseEventLoop.sock_connect(sock, address)
390
391 Connect to a remote socket at *address*.
392
Victor Stinner1b0580b2014-02-13 09:24:37 +0100393 The *address* must be already resolved to avoid the trap of hanging the
394 entire event loop when the address requires doing a DNS lookup. For
395 example, it must be an IP address, not an hostname, for
396 :py:data:`~socket.AF_INET` and :py:data:`~socket.AF_INET6` address families.
397 Use :meth:`getaddrinfo` to resolve the hostname asynchronously.
398
Victor Stinnerd84fd732014-08-26 01:01:59 +0200399 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
400 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200401
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500402 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100403
404 .. seealso::
405
406 The :meth:`BaseEventLoop.create_connection` method, the
407 :func:`open_connection` function and the :meth:`socket.socket.connect`
408 method.
409
410
411.. method:: BaseEventLoop.sock_accept(sock)
412
413 Accept a connection. The socket must be bound to an address and listening
414 for connections. The return value is a pair ``(conn, address)`` where *conn*
415 is a *new* socket object usable to send and receive data on the connection,
416 and *address* is the address bound to the socket on the other end of the
417 connection.
418
Victor Stinnerec2ce092014-07-29 23:12:22 +0200419 The socket *sock* must be non-blocking.
420
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500421 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100422
423 .. seealso::
424
425 The :meth:`BaseEventLoop.create_server` method, the :func:`start_server`
426 function and the :meth:`socket.socket.accept` method.
427
428
429Resolve host name
430-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100431
432.. method:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
433
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500434 This method is a :ref:`coroutine <coroutine>`, similar to
435 :meth:`socket.getaddrinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100436
437.. method:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
438
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500439 This method is a :ref:`coroutine <coroutine>`, similar to
440 :meth:`socket.getnameinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100441
442
Victor Stinner984600f2014-03-25 09:40:26 +0100443Connect pipes
444-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100445
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200446On Windows with :class:`SelectorEventLoop`, these methods are not supported.
447Use :class:`ProactorEventLoop` to support pipes on Windows.
448
Victor Stinnerea3183f2013-12-03 01:08:00 +0100449.. method:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
450
Victor Stinnerd84fd732014-08-26 01:01:59 +0200451 Register read pipe in eventloop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100452
453 *protocol_factory* should instantiate object with :class:`Protocol`
Victor Stinnera5b257a2014-05-29 00:14:03 +0200454 interface. *pipe* is a :term:`file-like object <file object>`.
455 Return pair ``(transport, protocol)``, where *transport* supports the
Victor Stinnerea3183f2013-12-03 01:08:00 +0100456 :class:`ReadTransport` interface.
457
Victor Stinnerd84fd732014-08-26 01:01:59 +0200458 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
459 non-blocking mode.
460
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500461 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100462
463.. method:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
464
465 Register write pipe in eventloop.
466
467 *protocol_factory* should instantiate object with :class:`BaseProtocol`
Victor Stinner2cef3002014-10-23 22:38:46 +0200468 interface. *pipe* is :term:`file-like object <file object>`.
469 Return pair ``(transport, protocol)``, where *transport* supports
Victor Stinnerea3183f2013-12-03 01:08:00 +0100470 :class:`WriteTransport` interface.
471
Victor Stinnerd84fd732014-08-26 01:01:59 +0200472 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
473 non-blocking mode.
474
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500475 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100476
Victor Stinner08444382014-02-02 22:43:39 +0100477.. seealso::
478
Victor Stinner984600f2014-03-25 09:40:26 +0100479 The :meth:`BaseEventLoop.subprocess_exec` and
480 :meth:`BaseEventLoop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100481
Victor Stinnerea3183f2013-12-03 01:08:00 +0100482
Victor Stinner8b863482014-01-27 10:07:50 +0100483UNIX signals
484------------
485
486Availability: UNIX only.
487
488.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
489
490 Add a handler for a signal.
491
492 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
493 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
494
495.. method:: BaseEventLoop.remove_signal_handler(sig)
496
497 Remove a handler for a signal.
498
499 Return ``True`` if a signal handler was removed, ``False`` if not.
500
501.. seealso::
502
503 The :mod:`signal` module.
504
505
Victor Stinnerea3183f2013-12-03 01:08:00 +0100506Executor
507--------
508
509Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
510pool of processes). By default, an event loop uses a thread pool executor
511(:class:`~concurrent.futures.ThreadPoolExecutor`).
512
513.. method:: BaseEventLoop.run_in_executor(executor, callback, \*args)
514
515 Arrange for a callback to be called in the specified executor.
516
Larry Hastings3732ed22014-03-15 21:13:56 -0700517 The *executor* argument should be an :class:`~concurrent.futures.Executor`
518 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100519
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500520 This method is a :ref:`coroutine <coroutine>`.
521
Victor Stinnerea3183f2013-12-03 01:08:00 +0100522.. method:: BaseEventLoop.set_default_executor(executor)
523
524 Set the default executor used by :meth:`run_in_executor`.
525
526
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500527Error Handling API
528------------------
529
530Allows to customize how exceptions are handled in the event loop.
531
532.. method:: BaseEventLoop.set_exception_handler(handler)
533
534 Set *handler* as the new event loop exception handler.
535
536 If *handler* is ``None``, the default exception handler will
537 be set.
538
539 If *handler* is a callable object, it should have a
540 matching signature to ``(loop, context)``, where ``loop``
541 will be a reference to the active event loop, ``context``
542 will be a ``dict`` object (see :meth:`call_exception_handler`
543 documentation for details about context).
544
545.. method:: BaseEventLoop.default_exception_handler(context)
546
547 Default exception handler.
548
549 This is called when an exception occurs and no exception
550 handler is set, and can be called by a custom exception
551 handler that wants to defer to the default behavior.
552
553 *context* parameter has the same meaning as in
554 :meth:`call_exception_handler`.
555
556.. method:: BaseEventLoop.call_exception_handler(context)
557
558 Call the current event loop exception handler.
559
560 *context* is a ``dict`` object containing the following keys
561 (new keys may be introduced later):
562
563 * 'message': Error message;
564 * 'exception' (optional): Exception object;
565 * 'future' (optional): :class:`asyncio.Future` instance;
566 * 'handle' (optional): :class:`asyncio.Handle` instance;
567 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
568 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
569 * 'socket' (optional): :class:`socket.socket` instance.
570
571 .. note::
572
573 Note: this method should not be overloaded in subclassed
574 event loops. For any custom exception handling, use
575 :meth:`set_exception_handler()` method.
576
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100577Debug mode
578----------
579
580.. method:: BaseEventLoop.get_debug()
581
Victor Stinner7b7120e2014-06-23 00:12:14 +0200582 Get the debug mode (:class:`bool`) of the event loop.
583
584 The default value is ``True`` if the environment variable
585 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
586 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100587
Victor Stinner64d750b2014-06-18 03:25:23 +0200588 .. versionadded:: 3.4.2
589
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100590.. method:: BaseEventLoop.set_debug(enabled: bool)
591
592 Set the debug mode of the event loop.
593
Victor Stinner64d750b2014-06-18 03:25:23 +0200594 .. versionadded:: 3.4.2
595
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100596.. seealso::
597
Victor Stinner62511fd2014-06-23 00:36:11 +0200598 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100599
Victor Stinner8c462c52014-01-24 18:11:43 +0100600Server
601------
602
Victor Stinner8ebeb032014-07-11 23:47:40 +0200603.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +0100604
Victor Stinner8ebeb032014-07-11 23:47:40 +0200605 Server listening on sockets.
606
607 Object created by the :meth:`BaseEventLoop.create_server` method and the
608 :func:`start_server` function. Don't instanciate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +0100609
610 .. method:: close()
611
Victor Stinner4bfb14a2014-07-12 03:20:24 +0200612 Stop serving: close listening sockets and set the :attr:`sockets`
613 attribute to ``None``.
614
615 The sockets that represent existing incoming client connections are
616 leaved open.
Victor Stinner8ebeb032014-07-11 23:47:40 +0200617
618 The server is closed asynchonously, use the :meth:`wait_closed` coroutine
619 to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100620
621 .. method:: wait_closed()
622
Victor Stinner8ebeb032014-07-11 23:47:40 +0200623 Wait until the :meth:`close` method completes.
624
625 This method is a :ref:`coroutine <coroutine>`.
626
627 .. attribute:: sockets
628
629 List of :class:`socket.socket` objects the server is listening to, or
630 ``None`` if the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100631
632
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500633Handle
634------
635
636.. class:: Handle
637
638 A callback wrapper object returned by :func:`BaseEventLoop.call_soon`,
639 :func:`BaseEventLoop.call_soon_threadsafe`, :func:`BaseEventLoop.call_later`,
640 and :func:`BaseEventLoop.call_at`.
641
642 .. method:: cancel()
643
Victor Stinneraea82292014-07-08 23:42:38 +0200644 Cancel the call.
645
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500646
Victor Stinner6888b962014-10-11 16:15:58 +0200647Event loop examples
648===================
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500649
Victor Stinner3e09e322013-12-03 01:22:06 +0100650.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100651
Victor Stinner7f314ed2014-10-15 18:49:16 +0200652Hello World with call_soon()
653----------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100654
Victor Stinner7f314ed2014-10-15 18:49:16 +0200655Example using the :meth:`BaseEventLoop.call_soon` method to schedule a
656callback. The callback displays ``"Hello World"`` and then stops the event
657loop::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100658
659 import asyncio
660
Victor Stinner7f314ed2014-10-15 18:49:16 +0200661 def hello_world(loop):
Victor Stinnerea3183f2013-12-03 01:08:00 +0100662 print('Hello World')
Victor Stinner7f314ed2014-10-15 18:49:16 +0200663 loop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100664
665 loop = asyncio.get_event_loop()
Victor Stinner7f314ed2014-10-15 18:49:16 +0200666
667 # Schedule a call to hello_world()
668 loop.call_soon(hello_world, loop)
669
670 # Blocking call interrupted by loop.stop()
671 loop.run_forever()
672 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100673
Victor Stinner3e09e322013-12-03 01:22:06 +0100674.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100675
Victor Stinner6888b962014-10-11 16:15:58 +0200676 The :ref:`Hello World coroutine <asyncio-hello-world-coroutine>` example
677 uses a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100678
Victor Stinner8b863482014-01-27 10:07:50 +0100679
Victor Stinner7f314ed2014-10-15 18:49:16 +0200680.. _asyncio-date-callback:
681
682Display the current date with call_later()
683------------------------------------------
684
685Example of callback displaying the current date every second. The callback uses
686the :meth:`BaseEventLoop.call_later` method to reschedule itself during 5
687seconds, and then stops the event loop::
688
689 import asyncio
690 import datetime
691
692 def display_date(end_time, loop):
693 print(datetime.datetime.now())
694 if (loop.time() + 1.0) < end_time:
695 loop.call_later(1, display_date, end_time, loop)
696 else:
697 loop.stop()
698
699 loop = asyncio.get_event_loop()
700
701 # Schedule the first call to display_date()
702 end_time = loop.time() + 5.0
703 loop.call_soon(display_date, end_time, loop)
704
705 # Blocking call interrupted by loop.stop()
706 loop.run_forever()
707 loop.close()
708
709.. seealso::
710
711 The :ref:`coroutine displaying the current date
712 <asyncio-date-coroutine>` example uses a :ref:`coroutine
713 <coroutine>`.
714
715
Victor Stinner04e6df32014-10-11 16:16:27 +0200716.. _asyncio-watch-read-event:
Victor Stinner8b863482014-01-27 10:07:50 +0100717
Victor Stinner04e6df32014-10-11 16:16:27 +0200718Watch a file descriptor for read events
719---------------------------------------
720
721Wait until a file descriptor received some data using the
722:meth:`BaseEventLoop.add_reader` method and then close the event loop::
723
724 import asyncio
Victor Stinnerccd8e342014-10-11 16:30:02 +0200725 try:
726 from socket import socketpair
727 except ImportError:
728 from asyncio.windows_utils import socketpair
Victor Stinner04e6df32014-10-11 16:16:27 +0200729
730 # Create a pair of connected file descriptors
Victor Stinnerccd8e342014-10-11 16:30:02 +0200731 rsock, wsock = socketpair()
Victor Stinner04e6df32014-10-11 16:16:27 +0200732 loop = asyncio.get_event_loop()
733
734 def reader():
735 data = rsock.recv(100)
736 print("Received:", data.decode())
Victor Stinner2cef3002014-10-23 22:38:46 +0200737 # We are done: unregister the file descriptor
Victor Stinner04e6df32014-10-11 16:16:27 +0200738 loop.remove_reader(rsock)
739 # Stop the event loop
740 loop.stop()
741
Victor Stinner2cef3002014-10-23 22:38:46 +0200742 # Register the file descriptor for read event
Victor Stinner04e6df32014-10-11 16:16:27 +0200743 loop.add_reader(rsock, reader)
744
745 # Simulate the reception of data from the network
746 loop.call_soon(wsock.send, 'abc'.encode())
747
748 # Run the event loop
749 loop.run_forever()
750
751 # We are done, close sockets and the event loop
752 rsock.close()
753 wsock.close()
754 loop.close()
755
756.. seealso::
757
758 The :ref:`register an open socket to wait for data using a protocol
759 <asyncio-register-socket>` example uses a low-level protocol created by the
760 :meth:`BaseEventLoop.create_connection` method.
761
762 The :ref:`register an open socket to wait for data using streams
763 <asyncio-register-socket-streams>` example uses high-level streams
764 created by the :func:`open_connection` function in a coroutine.
765
766
767Set signal handlers for SIGINT and SIGTERM
768------------------------------------------
769
770Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM` using
771the :meth:`BaseEventLoop.add_signal_handler` method::
Victor Stinner8b863482014-01-27 10:07:50 +0100772
773 import asyncio
774 import functools
775 import os
776 import signal
777
778 def ask_exit(signame):
779 print("got signal %s: exit" % signame)
780 loop.stop()
781
782 loop = asyncio.get_event_loop()
783 for signame in ('SIGINT', 'SIGTERM'):
784 loop.add_signal_handler(getattr(signal, signame),
785 functools.partial(ask_exit, signame))
786
787 print("Event loop running forever, press CTRL+c to interrupt.")
788 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
Victor Stinner63b21a82014-07-05 15:38:59 +0200789 try:
790 loop.run_forever()
791 finally:
792 loop.close()
Victor Stinner2cef3002014-10-23 22:38:46 +0200793
794This example only works on UNIX.