blob: 7717b7a1c71b8cba15aa93adc17bad273b2df80c [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
5Event loops
6===========
7
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
Eli Bendersky136fea22014-02-09 06:55:58 -080021Event loop policies and the default policy
22------------------------------------------
23
24Event loop management is abstracted with a *policy* pattern, to provide maximal
25flexibility for custom platforms and frameworks. Throughout the execution of a
26process, a single global policy object manages the event loops available to the
27process based on the calling context. A policy is an object implementing the
28:class:`AbstractEventLoopPolicy` interface.
29
30For most users of :mod:`asyncio`, policies never have to be dealt with
31explicitly, since the default global policy is sufficient.
32
33The default policy defines context as the current thread, and manages an event
34loop per thread that interacts with :mod:`asyncio`. The module-level functions
35:func:`get_event_loop` and :func:`set_event_loop` provide convenient access to
36event loops managed by the default policy.
37
Victor Stinnerea3183f2013-12-03 01:08:00 +010038Event loop functions
39--------------------
40
Eli Bendersky136fea22014-02-09 06:55:58 -080041The following functions are convenient shortcuts to accessing the methods of the
42global policy. Note that this provides access to the default policy, unless an
43alternative policy was set by calling :func:`set_event_loop_policy` earlier in
44the execution of the process.
Victor Stinnerea3183f2013-12-03 01:08:00 +010045
46.. function:: get_event_loop()
47
Eli Bendersky136fea22014-02-09 06:55:58 -080048 Equivalent to calling ``get_event_loop_policy().get_event_loop()``.
Victor Stinnerea3183f2013-12-03 01:08:00 +010049
50.. function:: set_event_loop(loop)
51
Eli Bendersky136fea22014-02-09 06:55:58 -080052 Equivalent to calling ``get_event_loop_policy().set_event_loop(loop)``.
Victor Stinnerea3183f2013-12-03 01:08:00 +010053
54.. function:: new_event_loop()
55
Eli Bendersky136fea22014-02-09 06:55:58 -080056 Equivalent to calling ``get_event_loop_policy().new_event_loop()``.
Victor Stinnerea3183f2013-12-03 01:08:00 +010057
Eli Bendersky136fea22014-02-09 06:55:58 -080058Event loop policy interface
59---------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +010060
Eli Bendersky136fea22014-02-09 06:55:58 -080061An event loop policy must implement the following interface:
62
63.. class:: AbstractEventLoopPolicy
64
65 .. method:: get_event_loop()
66
Victor Stinnerf9e49dd2014-06-05 12:06:44 +020067 Get the event loop for the current context. Returns an event loop object
68 implementing the :class:`BaseEventLoop` interface, or raises an exception in case
Eli Bendersky136fea22014-02-09 06:55:58 -080069 no event loop has been set for the current context and the current policy
70 does not specify to create one. It should never return ``None``.
71
72 .. method:: set_event_loop(loop)
73
Victor Stinnerf9e49dd2014-06-05 12:06:44 +020074 Set the event loop for the current context to *loop*.
Eli Bendersky136fea22014-02-09 06:55:58 -080075
76 .. method:: new_event_loop()
77
78 Create and return a new event loop object according to this policy's rules.
Victor Stinnerf9e49dd2014-06-05 12:06:44 +020079 If there's need to set this loop as the event loop for the current context,
Larry Hastingsad88d7a2014-02-10 04:26:10 -080080 :meth:`set_event_loop` must be called explicitly.
Eli Bendersky136fea22014-02-09 06:55:58 -080081
82Access to the global loop policy
83--------------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +010084
85.. function:: get_event_loop_policy()
86
Eli Bendersky136fea22014-02-09 06:55:58 -080087 Get the current event loop policy.
Victor Stinnerea3183f2013-12-03 01:08:00 +010088
89.. function:: set_event_loop_policy(policy)
90
Eli Bendersky136fea22014-02-09 06:55:58 -080091 Set the current event loop policy. If *policy* is ``None``, the default
92 policy is restored.
Victor Stinnerea3183f2013-12-03 01:08:00 +010093
94Run an event loop
95-----------------
96
97.. method:: BaseEventLoop.run_forever()
98
99 Run until :meth:`stop` is called.
100
101.. method:: BaseEventLoop.run_until_complete(future)
102
Victor Stinner99c2ab42013-12-03 19:17:25 +0100103 Run until the :class:`Future` is done.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100104
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500105 If the argument is a :ref:`coroutine <coroutine>`, it is wrapped
106 in a :class:`Task`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100107
108 Return the Future's result, or raise its exception.
109
110.. method:: BaseEventLoop.is_running()
111
112 Returns running status of event loop.
113
Victor Stinnerafbf8272013-12-03 02:05:42 +0100114.. method:: BaseEventLoop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100115
116 Stop running the event loop.
117
118 Every callback scheduled before :meth:`stop` is called will run.
119 Callback scheduled after :meth:`stop` is called won't. However, those
120 callbacks will run if :meth:`run_forever` is called again later.
121
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200122.. method:: BaseEventLoop.is_closed()
123
124 Returns ``True`` if the event loop was closed.
125
126 .. versionadded:: 3.4.2
127
Victor Stinnerea3183f2013-12-03 01:08:00 +0100128.. method:: BaseEventLoop.close()
129
130 Close the event loop. The loop should not be running.
131
132 This clears the queues and shuts down the executor, but does not wait for
133 the executor to finish.
134
135 This is idempotent and irreversible. No other methods should be called after
136 this one.
137
138
139Calls
140-----
141
142.. method:: BaseEventLoop.call_soon(callback, \*args)
143
144 Arrange for a callback to be called as soon as possible.
145
146 This operates as a FIFO queue, callbacks are called in the order in
147 which they are registered. Each callback will be called exactly once.
148
149 Any positional arguments after the callback will be passed to the
150 callback when it is called.
151
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500152 An instance of :class:`asyncio.Handle` is returned.
153
Victor Stinnerea3183f2013-12-03 01:08:00 +0100154.. method:: BaseEventLoop.call_soon_threadsafe(callback, \*args)
155
156 Like :meth:`call_soon`, but thread safe.
157
158
Victor Stinner45b27ed2014-02-01 02:36:43 +0100159.. _asyncio-delayed-calls:
160
Victor Stinnerea3183f2013-12-03 01:08:00 +0100161Delayed calls
162-------------
163
164The event loop has its own internal clock for computing timeouts.
165Which clock is used depends on the (platform-specific) event loop
166implementation; ideally it is a monotonic clock. This will generally be
167a different clock than :func:`time.time`.
168
Victor Stinnerfd9d3742014-02-18 09:37:43 +0100169.. note::
170
171 Timeouts (relative *delay* or absolute *when*) should not exceed one day.
172
Victor Stinner45b27ed2014-02-01 02:36:43 +0100173
Victor Stinnerea3183f2013-12-03 01:08:00 +0100174.. method:: BaseEventLoop.call_later(delay, callback, *args)
175
176 Arrange for the *callback* to be called after the given *delay*
177 seconds (either an int or float).
178
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500179 An instance of :class:`asyncio.Handle` is returned.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100180
181 *callback* will be called exactly once per call to :meth:`call_later`.
182 If two callbacks are scheduled for exactly the same time, it is
183 undefined which will be called first.
184
185 The optional positional *args* will be passed to the callback when it
186 is called. If you want the callback to be called with some named
187 arguments, use a closure or :func:`functools.partial`.
188
189.. method:: BaseEventLoop.call_at(when, callback, *args)
190
191 Arrange for the *callback* to be called at the given absolute timestamp
192 *when* (an int or float), using the same time reference as :meth:`time`.
193
194 This method's behavior is the same as :meth:`call_later`.
195
196.. method:: BaseEventLoop.time()
197
198 Return the current time, as a :class:`float` value, according to the
199 event loop's internal clock.
200
Victor Stinner3e09e322013-12-03 01:22:06 +0100201.. seealso::
202
203 The :func:`asyncio.sleep` function.
204
Victor Stinnerea3183f2013-12-03 01:08:00 +0100205
206Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100207--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100208
209.. 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)
210
211 Create a streaming transport connection to a given Internet *host* and
Victor Stinnera6919aa2014-02-19 13:32:34 +0100212 *port*: socket family :py:data:`~socket.AF_INET` or
213 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
214 socket type :py:data:`~socket.SOCK_STREAM`. *protocol_factory* must be a
215 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100216
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500217 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100218 establish the connection in the background. When successful, the
219 coroutine returns a ``(transport, protocol)`` pair.
220
221 The chronological synopsis of the underlying operation is as follows:
222
Victor Stinner9592edb2014-02-02 15:03:02 +0100223 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100224 is created to represent it.
225
226 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100227 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100228
229 #. The protocol instance is tied to the transport, and its
230 :meth:`connection_made` method is called.
231
232 #. The coroutine returns successfully with the ``(transport, protocol)``
233 pair.
234
235 The created transport is an implementation-dependent bidirectional stream.
236
237 .. note::
238 *protocol_factory* can be any kind of callable, not necessarily
239 a class. For example, if you want to use a pre-created
240 protocol instance, you can pass ``lambda: my_protocol``.
241
242 Options allowing to change how the connection is created:
243
244 * *ssl*: if given and not false, a SSL/TLS transport is created
245 (by default a plain TCP transport is created). If *ssl* is
246 a :class:`ssl.SSLContext` object, this context is used to create
247 the transport; if *ssl* is :const:`True`, a context with some
248 unspecified default settings is used.
249
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100250 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
251
Victor Stinnerea3183f2013-12-03 01:08:00 +0100252 * *server_hostname*, is only for use together with *ssl*,
253 and sets or overrides the hostname that the target server's certificate
254 will be matched against. By default the value of the *host* argument
255 is used. If *host* is empty, there is no default and you must pass a
256 value for *server_hostname*. If *server_hostname* is an empty
257 string, hostname matching is disabled (which is a serious security
258 risk, allowing for man-in-the-middle-attacks).
259
260 * *family*, *proto*, *flags* are the optional address family, protocol
261 and flags to be passed through to getaddrinfo() for *host* resolution.
262 If given, these should all be integers from the corresponding
263 :mod:`socket` module constants.
264
265 * *sock*, if given, should be an existing, already connected
266 :class:`socket.socket` object to be used by the transport.
267 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
268 and *local_addr* should be specified.
269
270 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
271 to bind the socket to locally. The *local_host* and *local_port*
272 are looked up using getaddrinfo(), similarly to *host* and *port*.
273
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100274 .. seealso::
275
276 The :func:`open_connection` function can be used to get a pair of
277 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
278
Victor Stinnerea3183f2013-12-03 01:08:00 +0100279
Victor Stinnera6919aa2014-02-19 13:32:34 +0100280.. method:: BaseEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0)
281
282 Create datagram connection: socket family :py:data:`~socket.AF_INET` or
283 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
284 socket type :py:data:`~socket.SOCK_DGRAM`.
285
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500286 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100287 establish the connection in the background. When successful, the
288 coroutine returns a ``(transport, protocol)`` pair.
289
290 See the :meth:`BaseEventLoop.create_connection` method for parameters.
291
292
293.. method:: BaseEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
294
295 Create UNIX connection: socket family :py:data:`~socket.AF_UNIX`, socket
296 type :py:data:`~socket.SOCK_STREAM`. The :py:data:`~socket.AF_UNIX` socket
297 family is used to communicate between processes on the same machine
298 efficiently.
299
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500300 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100301 establish the connection in the background. When successful, the
302 coroutine returns a ``(transport, protocol)`` pair.
303
304 See the :meth:`BaseEventLoop.create_connection` method for parameters.
305
306 Availability: UNIX.
307
308
Victor Stinnerea3183f2013-12-03 01:08:00 +0100309Creating listening connections
310------------------------------
311
312.. 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)
313
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500314 A :ref:`coroutine <coroutine>` method which creates a TCP server bound to
315 host and port.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100316
317 The return value is a :class:`AbstractServer` object which can be used to stop
318 the service.
319
320 If *host* is an empty string or None all interfaces are assumed
321 and a list of multiple sockets will be returned (most likely
322 one for IPv4 and another one for IPv6).
323
324 *family* can be set to either :data:`~socket.AF_INET` or
325 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
326 it will be determined from host (defaults to :data:`~socket.AF_UNSPEC`).
327
328 *flags* is a bitmask for :meth:`getaddrinfo`.
329
330 *sock* can optionally be specified in order to use a preexisting
331 socket object.
332
333 *backlog* is the maximum number of queued connections passed to
334 :meth:`~socket.socket.listen` (defaults to 100).
335
336 ssl can be set to an :class:`~ssl.SSLContext` to enable SSL over the
337 accepted connections.
338
339 *reuse_address* tells the kernel to reuse a local socket in
340 TIME_WAIT state, without waiting for its natural timeout to
341 expire. If not specified will automatically be set to True on
342 UNIX.
343
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100344 .. seealso::
345
346 The function :func:`start_server` creates a (:class:`StreamReader`,
347 :class:`StreamWriter`) pair and calls back a function with this pair.
348
Victor Stinnerea3183f2013-12-03 01:08:00 +0100349
Victor Stinnera6919aa2014-02-19 13:32:34 +0100350.. method:: BaseEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100351
Victor Stinnera6919aa2014-02-19 13:32:34 +0100352 Similar to :meth:`BaseEventLoop.create_server`, but specific to the
353 socket family :py:data:`~socket.AF_UNIX`.
354
355 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100356
357
358
Victor Stinnerc1567df2014-02-08 23:22:58 +0100359Watch file descriptors
360----------------------
361
362.. method:: BaseEventLoop.add_reader(fd, callback, \*args)
363
364 Start watching the file descriptor for read availability and then call the
365 *callback* with specified arguments.
366
367.. method:: BaseEventLoop.remove_reader(fd)
368
369 Stop watching the file descriptor for read availability.
370
371.. method:: BaseEventLoop.add_writer(fd, callback, \*args)
372
373 Start watching the file descriptor for write availability and then call the
374 *callback* with specified arguments.
375
376.. method:: BaseEventLoop.remove_writer(fd)
377
378 Stop watching the file descriptor for write availability.
379
380
381Low-level socket operations
382---------------------------
383
384.. method:: BaseEventLoop.sock_recv(sock, nbytes)
385
386 Receive data from the socket. The return value is a bytes object
387 representing the data received. The maximum amount of data to be received
388 at once is specified by *nbytes*.
389
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500390 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100391
392 .. seealso::
393
394 The :meth:`socket.socket.recv` method.
395
396.. method:: BaseEventLoop.sock_sendall(sock, data)
397
398 Send data to the socket. The socket must be connected to a remote socket.
399 This method continues to send data from *data* until either all data has
400 been sent or an error occurs. ``None`` is returned on success. On error,
401 an exception is raised, and there is no way to determine how much data, if
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500402 any, was successfully processed by the receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100403
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500404 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100405
406 .. seealso::
407
408 The :meth:`socket.socket.sendall` method.
409
410.. method:: BaseEventLoop.sock_connect(sock, address)
411
412 Connect to a remote socket at *address*.
413
Victor Stinner1b0580b2014-02-13 09:24:37 +0100414 The *address* must be already resolved to avoid the trap of hanging the
415 entire event loop when the address requires doing a DNS lookup. For
416 example, it must be an IP address, not an hostname, for
417 :py:data:`~socket.AF_INET` and :py:data:`~socket.AF_INET6` address families.
418 Use :meth:`getaddrinfo` to resolve the hostname asynchronously.
419
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500420 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100421
422 .. seealso::
423
424 The :meth:`BaseEventLoop.create_connection` method, the
425 :func:`open_connection` function and the :meth:`socket.socket.connect`
426 method.
427
428
429.. method:: BaseEventLoop.sock_accept(sock)
430
431 Accept a connection. The socket must be bound to an address and listening
432 for connections. The return value is a pair ``(conn, address)`` where *conn*
433 is a *new* socket object usable to send and receive data on the connection,
434 and *address* is the address bound to the socket on the other end of the
435 connection.
436
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500437 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100438
439 .. seealso::
440
441 The :meth:`BaseEventLoop.create_server` method, the :func:`start_server`
442 function and the :meth:`socket.socket.accept` method.
443
444
445Resolve host name
446-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100447
448.. method:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
449
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500450 This method is a :ref:`coroutine <coroutine>`, similar to
451 :meth:`socket.getaddrinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100452
453.. method:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
454
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500455 This method is a :ref:`coroutine <coroutine>`, similar to
456 :meth:`socket.getnameinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100457
458
Victor Stinner984600f2014-03-25 09:40:26 +0100459Connect pipes
460-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100461
462.. method:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
463
Victor Stinnera5b257a2014-05-29 00:14:03 +0200464 Register read pipe in eventloop. Set the *pipe* to non-blocking mode.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100465
466 *protocol_factory* should instantiate object with :class:`Protocol`
Victor Stinnera5b257a2014-05-29 00:14:03 +0200467 interface. *pipe* is a :term:`file-like object <file object>`.
468 Return pair ``(transport, protocol)``, where *transport* supports the
Victor Stinnerea3183f2013-12-03 01:08:00 +0100469 :class:`ReadTransport` interface.
470
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500471 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100472
473.. method:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
474
475 Register write pipe in eventloop.
476
477 *protocol_factory* should instantiate object with :class:`BaseProtocol`
478 interface. Pipe is file-like object already switched to nonblocking.
479 Return pair (transport, protocol), where transport support
480 :class:`WriteTransport` interface.
481
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500482 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100483
Victor Stinner08444382014-02-02 22:43:39 +0100484.. seealso::
485
Victor Stinner984600f2014-03-25 09:40:26 +0100486 The :meth:`BaseEventLoop.subprocess_exec` and
487 :meth:`BaseEventLoop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100488
Victor Stinnerea3183f2013-12-03 01:08:00 +0100489
Victor Stinner8b863482014-01-27 10:07:50 +0100490UNIX signals
491------------
492
493Availability: UNIX only.
494
495.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
496
497 Add a handler for a signal.
498
499 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
500 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
501
502.. method:: BaseEventLoop.remove_signal_handler(sig)
503
504 Remove a handler for a signal.
505
506 Return ``True`` if a signal handler was removed, ``False`` if not.
507
508.. seealso::
509
510 The :mod:`signal` module.
511
512
Victor Stinnerea3183f2013-12-03 01:08:00 +0100513Executor
514--------
515
516Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
517pool of processes). By default, an event loop uses a thread pool executor
518(:class:`~concurrent.futures.ThreadPoolExecutor`).
519
520.. method:: BaseEventLoop.run_in_executor(executor, callback, \*args)
521
522 Arrange for a callback to be called in the specified executor.
523
Larry Hastings3732ed22014-03-15 21:13:56 -0700524 The *executor* argument should be an :class:`~concurrent.futures.Executor`
525 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100526
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500527 This method is a :ref:`coroutine <coroutine>`.
528
Victor Stinnerea3183f2013-12-03 01:08:00 +0100529.. method:: BaseEventLoop.set_default_executor(executor)
530
531 Set the default executor used by :meth:`run_in_executor`.
532
533
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500534Error Handling API
535------------------
536
537Allows to customize how exceptions are handled in the event loop.
538
539.. method:: BaseEventLoop.set_exception_handler(handler)
540
541 Set *handler* as the new event loop exception handler.
542
543 If *handler* is ``None``, the default exception handler will
544 be set.
545
546 If *handler* is a callable object, it should have a
547 matching signature to ``(loop, context)``, where ``loop``
548 will be a reference to the active event loop, ``context``
549 will be a ``dict`` object (see :meth:`call_exception_handler`
550 documentation for details about context).
551
552.. method:: BaseEventLoop.default_exception_handler(context)
553
554 Default exception handler.
555
556 This is called when an exception occurs and no exception
557 handler is set, and can be called by a custom exception
558 handler that wants to defer to the default behavior.
559
560 *context* parameter has the same meaning as in
561 :meth:`call_exception_handler`.
562
563.. method:: BaseEventLoop.call_exception_handler(context)
564
565 Call the current event loop exception handler.
566
567 *context* is a ``dict`` object containing the following keys
568 (new keys may be introduced later):
569
570 * 'message': Error message;
571 * 'exception' (optional): Exception object;
572 * 'future' (optional): :class:`asyncio.Future` instance;
573 * 'handle' (optional): :class:`asyncio.Handle` instance;
574 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
575 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
576 * 'socket' (optional): :class:`socket.socket` instance.
577
578 .. note::
579
580 Note: this method should not be overloaded in subclassed
581 event loops. For any custom exception handling, use
582 :meth:`set_exception_handler()` method.
583
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100584Debug mode
585----------
586
587.. method:: BaseEventLoop.get_debug()
588
Victor Stinner1415e252014-02-20 01:44:10 +0100589 Get the debug mode (:class:`bool`) of the event loop, ``False`` by default.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100590
591.. method:: BaseEventLoop.set_debug(enabled: bool)
592
593 Set the debug mode of the event loop.
594
595.. seealso::
596
597 The :ref:`Develop with asyncio <asyncio-dev>` section.
598
599
Victor Stinner8c462c52014-01-24 18:11:43 +0100600Server
601------
602
603.. class:: AbstractServer
604
605 Abstract server returned by :func:`BaseEventLoop.create_server`.
606
607 .. method:: close()
608
609 Stop serving. This leaves existing connections open.
610
611 .. method:: wait_closed()
612
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500613 A :ref:`coroutine <coroutine>` to wait until service is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100614
615
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500616Handle
617------
618
619.. class:: Handle
620
621 A callback wrapper object returned by :func:`BaseEventLoop.call_soon`,
622 :func:`BaseEventLoop.call_soon_threadsafe`, :func:`BaseEventLoop.call_later`,
623 and :func:`BaseEventLoop.call_at`.
624
625 .. method:: cancel()
626
627 Cancel the call.
628
629
Victor Stinner3e09e322013-12-03 01:22:06 +0100630.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100631
Victor Stinner3e09e322013-12-03 01:22:06 +0100632Example: Hello World (callback)
633-------------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100634
635Print ``Hello World`` every two seconds, using a callback::
636
637 import asyncio
638
639 def print_and_repeat(loop):
640 print('Hello World')
641 loop.call_later(2, print_and_repeat, loop)
642
643 loop = asyncio.get_event_loop()
Victor Stinnerdbd89502013-12-10 02:47:22 +0100644 loop.call_soon(print_and_repeat, loop)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100645 loop.run_forever()
646
Victor Stinner3e09e322013-12-03 01:22:06 +0100647.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100648
Victor Stinner3e09e322013-12-03 01:22:06 +0100649 :ref:`Hello World example using a coroutine <asyncio-hello-world-coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100650
Victor Stinner8b863482014-01-27 10:07:50 +0100651
652Example: Set signal handlers for SIGINT and SIGTERM
653---------------------------------------------------
654
655Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`::
656
657 import asyncio
658 import functools
659 import os
660 import signal
661
662 def ask_exit(signame):
663 print("got signal %s: exit" % signame)
664 loop.stop()
665
666 loop = asyncio.get_event_loop()
667 for signame in ('SIGINT', 'SIGTERM'):
668 loop.add_signal_handler(getattr(signal, signame),
669 functools.partial(ask_exit, signame))
670
671 print("Event loop running forever, press CTRL+c to interrupt.")
672 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
673 loop.run_forever()
674