blob: 8706b41ff4702cca96b981d791d47c679f38f37a [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
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100200 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
201
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 Stinnera6919aa2014-02-19 13:32:34 +0100246
247.. method:: BaseEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
248
249 Create UNIX connection: socket family :py:data:`~socket.AF_UNIX`, socket
250 type :py:data:`~socket.SOCK_STREAM`. The :py:data:`~socket.AF_UNIX` socket
251 family is used to communicate between processes on the same machine
252 efficiently.
253
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500254 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100255 establish the connection in the background. When successful, the
256 coroutine returns a ``(transport, protocol)`` pair.
257
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200258 On Windows with :class:`ProactorEventLoop`, SSL/TLS is not supported.
259
Victor Stinnera6919aa2014-02-19 13:32:34 +0100260 See the :meth:`BaseEventLoop.create_connection` method for parameters.
261
262 Availability: UNIX.
263
264
Victor Stinnerea3183f2013-12-03 01:08:00 +0100265Creating listening connections
266------------------------------
267
268.. 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)
269
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200270 Create a TCP server bound to *host* and *port*. Return a :class:`Server` object,
Victor Stinner8ebeb032014-07-11 23:47:40 +0200271 its :attr:`~Server.sockets` attribute contains created sockets. Use the
272 :meth:`Server.close` method to stop the server: close listening sockets.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100273
Victor Stinnerd1432092014-06-19 17:11:49 +0200274 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100275
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200276 If *host* is an empty string or ``None``, all interfaces are assumed
Victor Stinnerea3183f2013-12-03 01:08:00 +0100277 and a list of multiple sockets will be returned (most likely
278 one for IPv4 and another one for IPv6).
279
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200280 *family* can be set to either :data:`socket.AF_INET` or
Victor Stinnerea3183f2013-12-03 01:08:00 +0100281 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200282 it will be determined from host (defaults to :data:`socket.AF_UNSPEC`).
Victor Stinnerea3183f2013-12-03 01:08:00 +0100283
284 *flags* is a bitmask for :meth:`getaddrinfo`.
285
286 *sock* can optionally be specified in order to use a preexisting
287 socket object.
288
289 *backlog* is the maximum number of queued connections passed to
290 :meth:`~socket.socket.listen` (defaults to 100).
291
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200292 *ssl* can be set to an :class:`~ssl.SSLContext` to enable SSL over the
Victor Stinnerea3183f2013-12-03 01:08:00 +0100293 accepted connections.
294
295 *reuse_address* tells the kernel to reuse a local socket in
296 TIME_WAIT state, without waiting for its natural timeout to
297 expire. If not specified will automatically be set to True on
298 UNIX.
299
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200300 On Windows with :class:`ProactorEventLoop`, SSL/TLS is not supported.
301
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100302 .. seealso::
303
304 The function :func:`start_server` creates a (:class:`StreamReader`,
305 :class:`StreamWriter`) pair and calls back a function with this pair.
306
Victor Stinnerea3183f2013-12-03 01:08:00 +0100307
Victor Stinnera6919aa2014-02-19 13:32:34 +0100308.. method:: BaseEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100309
Victor Stinnera6919aa2014-02-19 13:32:34 +0100310 Similar to :meth:`BaseEventLoop.create_server`, but specific to the
311 socket family :py:data:`~socket.AF_UNIX`.
312
313 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100314
315
Victor Stinnerc1567df2014-02-08 23:22:58 +0100316Watch file descriptors
317----------------------
318
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200319On Windows with :class:`SelectorEventLoop`, only socket handles are supported
320(ex: pipe file descriptors are not supported).
321
322On Windows with :class:`ProactorEventLoop`, these methods are not supported.
323
Victor Stinnerc1567df2014-02-08 23:22:58 +0100324.. method:: BaseEventLoop.add_reader(fd, callback, \*args)
325
326 Start watching the file descriptor for read availability and then call the
327 *callback* with specified arguments.
328
329.. method:: BaseEventLoop.remove_reader(fd)
330
331 Stop watching the file descriptor for read availability.
332
333.. method:: BaseEventLoop.add_writer(fd, callback, \*args)
334
335 Start watching the file descriptor for write availability and then call the
336 *callback* with specified arguments.
337
338.. method:: BaseEventLoop.remove_writer(fd)
339
340 Stop watching the file descriptor for write availability.
341
342
343Low-level socket operations
344---------------------------
345
346.. method:: BaseEventLoop.sock_recv(sock, nbytes)
347
348 Receive data from the socket. The return value is a bytes object
349 representing the data received. The maximum amount of data to be received
350 at once is specified by *nbytes*.
351
Victor Stinnerd84fd732014-08-26 01:01:59 +0200352 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
353 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200354
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500355 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100356
357 .. seealso::
358
359 The :meth:`socket.socket.recv` method.
360
361.. method:: BaseEventLoop.sock_sendall(sock, data)
362
363 Send data to the socket. The socket must be connected to a remote socket.
364 This method continues to send data from *data* until either all data has
365 been sent or an error occurs. ``None`` is returned on success. On error,
366 an exception is raised, and there is no way to determine how much data, if
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500367 any, was successfully processed by the receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100368
Victor Stinnerd84fd732014-08-26 01:01:59 +0200369 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
370 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200371
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500372 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100373
374 .. seealso::
375
376 The :meth:`socket.socket.sendall` method.
377
378.. method:: BaseEventLoop.sock_connect(sock, address)
379
380 Connect to a remote socket at *address*.
381
Victor Stinner1b0580b2014-02-13 09:24:37 +0100382 The *address* must be already resolved to avoid the trap of hanging the
383 entire event loop when the address requires doing a DNS lookup. For
384 example, it must be an IP address, not an hostname, for
385 :py:data:`~socket.AF_INET` and :py:data:`~socket.AF_INET6` address families.
386 Use :meth:`getaddrinfo` to resolve the hostname asynchronously.
387
Victor Stinnerd84fd732014-08-26 01:01:59 +0200388 With :class:`SelectorEventLoop` event loop, the socket *sock* must be
389 non-blocking.
Victor Stinnerec2ce092014-07-29 23:12:22 +0200390
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500391 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100392
393 .. seealso::
394
395 The :meth:`BaseEventLoop.create_connection` method, the
396 :func:`open_connection` function and the :meth:`socket.socket.connect`
397 method.
398
399
400.. method:: BaseEventLoop.sock_accept(sock)
401
402 Accept a connection. The socket must be bound to an address and listening
403 for connections. The return value is a pair ``(conn, address)`` where *conn*
404 is a *new* socket object usable to send and receive data on the connection,
405 and *address* is the address bound to the socket on the other end of the
406 connection.
407
Victor Stinnerec2ce092014-07-29 23:12:22 +0200408 The socket *sock* must be non-blocking.
409
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500410 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100411
412 .. seealso::
413
414 The :meth:`BaseEventLoop.create_server` method, the :func:`start_server`
415 function and the :meth:`socket.socket.accept` method.
416
417
418Resolve host name
419-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100420
421.. method:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
422
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500423 This method is a :ref:`coroutine <coroutine>`, similar to
424 :meth:`socket.getaddrinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100425
426.. method:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
427
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500428 This method is a :ref:`coroutine <coroutine>`, similar to
429 :meth:`socket.getnameinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100430
431
Victor Stinner984600f2014-03-25 09:40:26 +0100432Connect pipes
433-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100434
Victor Stinner41f3c3f2014-08-31 14:47:37 +0200435On Windows with :class:`SelectorEventLoop`, these methods are not supported.
436Use :class:`ProactorEventLoop` to support pipes on Windows.
437
Victor Stinnerea3183f2013-12-03 01:08:00 +0100438.. method:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
439
Victor Stinnerd84fd732014-08-26 01:01:59 +0200440 Register read pipe in eventloop.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100441
442 *protocol_factory* should instantiate object with :class:`Protocol`
Victor Stinnera5b257a2014-05-29 00:14:03 +0200443 interface. *pipe* is a :term:`file-like object <file object>`.
444 Return pair ``(transport, protocol)``, where *transport* supports the
Victor Stinnerea3183f2013-12-03 01:08:00 +0100445 :class:`ReadTransport` interface.
446
Victor Stinnerd84fd732014-08-26 01:01:59 +0200447 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
448 non-blocking mode.
449
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500450 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100451
452.. method:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
453
454 Register write pipe in eventloop.
455
456 *protocol_factory* should instantiate object with :class:`BaseProtocol`
Victor Stinnerd84fd732014-08-26 01:01:59 +0200457 interface. *pipe* is file-like object.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100458 Return pair (transport, protocol), where transport support
459 :class:`WriteTransport` interface.
460
Victor Stinnerd84fd732014-08-26 01:01:59 +0200461 With :class:`SelectorEventLoop` event loop, the *pipe* is set to
462 non-blocking mode.
463
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500464 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100465
Victor Stinner08444382014-02-02 22:43:39 +0100466.. seealso::
467
Victor Stinner984600f2014-03-25 09:40:26 +0100468 The :meth:`BaseEventLoop.subprocess_exec` and
469 :meth:`BaseEventLoop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100470
Victor Stinnerea3183f2013-12-03 01:08:00 +0100471
Victor Stinner8b863482014-01-27 10:07:50 +0100472UNIX signals
473------------
474
475Availability: UNIX only.
476
477.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
478
479 Add a handler for a signal.
480
481 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
482 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
483
484.. method:: BaseEventLoop.remove_signal_handler(sig)
485
486 Remove a handler for a signal.
487
488 Return ``True`` if a signal handler was removed, ``False`` if not.
489
490.. seealso::
491
492 The :mod:`signal` module.
493
494
Victor Stinnerea3183f2013-12-03 01:08:00 +0100495Executor
496--------
497
498Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
499pool of processes). By default, an event loop uses a thread pool executor
500(:class:`~concurrent.futures.ThreadPoolExecutor`).
501
502.. method:: BaseEventLoop.run_in_executor(executor, callback, \*args)
503
504 Arrange for a callback to be called in the specified executor.
505
Larry Hastings3732ed22014-03-15 21:13:56 -0700506 The *executor* argument should be an :class:`~concurrent.futures.Executor`
507 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100508
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500509 This method is a :ref:`coroutine <coroutine>`.
510
Victor Stinnerea3183f2013-12-03 01:08:00 +0100511.. method:: BaseEventLoop.set_default_executor(executor)
512
513 Set the default executor used by :meth:`run_in_executor`.
514
515
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500516Error Handling API
517------------------
518
519Allows to customize how exceptions are handled in the event loop.
520
521.. method:: BaseEventLoop.set_exception_handler(handler)
522
523 Set *handler* as the new event loop exception handler.
524
525 If *handler* is ``None``, the default exception handler will
526 be set.
527
528 If *handler* is a callable object, it should have a
529 matching signature to ``(loop, context)``, where ``loop``
530 will be a reference to the active event loop, ``context``
531 will be a ``dict`` object (see :meth:`call_exception_handler`
532 documentation for details about context).
533
534.. method:: BaseEventLoop.default_exception_handler(context)
535
536 Default exception handler.
537
538 This is called when an exception occurs and no exception
539 handler is set, and can be called by a custom exception
540 handler that wants to defer to the default behavior.
541
542 *context* parameter has the same meaning as in
543 :meth:`call_exception_handler`.
544
545.. method:: BaseEventLoop.call_exception_handler(context)
546
547 Call the current event loop exception handler.
548
549 *context* is a ``dict`` object containing the following keys
550 (new keys may be introduced later):
551
552 * 'message': Error message;
553 * 'exception' (optional): Exception object;
554 * 'future' (optional): :class:`asyncio.Future` instance;
555 * 'handle' (optional): :class:`asyncio.Handle` instance;
556 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
557 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
558 * 'socket' (optional): :class:`socket.socket` instance.
559
560 .. note::
561
562 Note: this method should not be overloaded in subclassed
563 event loops. For any custom exception handling, use
564 :meth:`set_exception_handler()` method.
565
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100566Debug mode
567----------
568
569.. method:: BaseEventLoop.get_debug()
570
Victor Stinner7b7120e2014-06-23 00:12:14 +0200571 Get the debug mode (:class:`bool`) of the event loop.
572
573 The default value is ``True`` if the environment variable
574 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
575 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100576
Victor Stinner64d750b2014-06-18 03:25:23 +0200577 .. versionadded:: 3.4.2
578
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100579.. method:: BaseEventLoop.set_debug(enabled: bool)
580
581 Set the debug mode of the event loop.
582
Victor Stinner64d750b2014-06-18 03:25:23 +0200583 .. versionadded:: 3.4.2
584
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100585.. seealso::
586
Victor Stinner62511fd2014-06-23 00:36:11 +0200587 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100588
Victor Stinner8c462c52014-01-24 18:11:43 +0100589Server
590------
591
Victor Stinner8ebeb032014-07-11 23:47:40 +0200592.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +0100593
Victor Stinner8ebeb032014-07-11 23:47:40 +0200594 Server listening on sockets.
595
596 Object created by the :meth:`BaseEventLoop.create_server` method and the
597 :func:`start_server` function. Don't instanciate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +0100598
599 .. method:: close()
600
Victor Stinner4bfb14a2014-07-12 03:20:24 +0200601 Stop serving: close listening sockets and set the :attr:`sockets`
602 attribute to ``None``.
603
604 The sockets that represent existing incoming client connections are
605 leaved open.
Victor Stinner8ebeb032014-07-11 23:47:40 +0200606
607 The server is closed asynchonously, use the :meth:`wait_closed` coroutine
608 to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100609
610 .. method:: wait_closed()
611
Victor Stinner8ebeb032014-07-11 23:47:40 +0200612 Wait until the :meth:`close` method completes.
613
614 This method is a :ref:`coroutine <coroutine>`.
615
616 .. attribute:: sockets
617
618 List of :class:`socket.socket` objects the server is listening to, or
619 ``None`` if the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100620
621
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500622Handle
623------
624
625.. class:: Handle
626
627 A callback wrapper object returned by :func:`BaseEventLoop.call_soon`,
628 :func:`BaseEventLoop.call_soon_threadsafe`, :func:`BaseEventLoop.call_later`,
629 and :func:`BaseEventLoop.call_at`.
630
631 .. method:: cancel()
632
Victor Stinneraea82292014-07-08 23:42:38 +0200633 Cancel the call.
634
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500635
636
Victor Stinner3e09e322013-12-03 01:22:06 +0100637.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100638
Victor Stinner3e09e322013-12-03 01:22:06 +0100639Example: Hello World (callback)
640-------------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100641
642Print ``Hello World`` every two seconds, using a callback::
643
644 import asyncio
645
646 def print_and_repeat(loop):
647 print('Hello World')
648 loop.call_later(2, print_and_repeat, loop)
649
650 loop = asyncio.get_event_loop()
Victor Stinnerdbd89502013-12-10 02:47:22 +0100651 loop.call_soon(print_and_repeat, loop)
Victor Stinner63b21a82014-07-05 15:38:59 +0200652 try:
653 loop.run_forever()
654 finally:
655 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100656
Victor Stinner3e09e322013-12-03 01:22:06 +0100657.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100658
Victor Stinner3e09e322013-12-03 01:22:06 +0100659 :ref:`Hello World example using a coroutine <asyncio-hello-world-coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100660
Victor Stinner8b863482014-01-27 10:07:50 +0100661
662Example: Set signal handlers for SIGINT and SIGTERM
663---------------------------------------------------
664
665Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`::
666
667 import asyncio
668 import functools
669 import os
670 import signal
671
672 def ask_exit(signame):
673 print("got signal %s: exit" % signame)
674 loop.stop()
675
676 loop = asyncio.get_event_loop()
677 for signame in ('SIGINT', 'SIGTERM'):
678 loop.add_signal_handler(getattr(signal, signame),
679 functools.partial(ask_exit, signame))
680
681 print("Event loop running forever, press CTRL+c to interrupt.")
682 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
Victor Stinner63b21a82014-07-05 15:38:59 +0200683 try:
684 loop.run_forever()
685 finally:
686 loop.close()
Victor Stinner8b863482014-01-27 10:07:50 +0100687