blob: 88fe35e96667c22f8c7dda8bd1cbc1418f7b8b89 [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
67 Get the event loop for current context. Returns an event loop object
68 implementing :class:`BaseEventLoop` interface, or raises an exception in case
69 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
74 Set the event loop of the current context to *loop*.
75
76 .. method:: new_event_loop()
77
78 Create and return a new event loop object according to this policy's rules.
79 If there's need to set this loop as the event loop of 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
105 If the argument is a coroutine, it is wrapped in a :class:`Task`.
106
107 Return the Future's result, or raise its exception.
108
109.. method:: BaseEventLoop.is_running()
110
111 Returns running status of event loop.
112
Victor Stinnerafbf8272013-12-03 02:05:42 +0100113.. method:: BaseEventLoop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100114
115 Stop running the event loop.
116
117 Every callback scheduled before :meth:`stop` is called will run.
118 Callback scheduled after :meth:`stop` is called won't. However, those
119 callbacks will run if :meth:`run_forever` is called again later.
120
121.. method:: BaseEventLoop.close()
122
123 Close the event loop. The loop should not be running.
124
125 This clears the queues and shuts down the executor, but does not wait for
126 the executor to finish.
127
128 This is idempotent and irreversible. No other methods should be called after
129 this one.
130
131
132Calls
133-----
134
135.. method:: BaseEventLoop.call_soon(callback, \*args)
136
137 Arrange for a callback to be called as soon as possible.
138
139 This operates as a FIFO queue, callbacks are called in the order in
140 which they are registered. Each callback will be called exactly once.
141
142 Any positional arguments after the callback will be passed to the
143 callback when it is called.
144
Yury Selivanovd5797422014-02-19 20:58:44 -0500145 An instance of :class:`asyncio.Handle` is returned.
146
Victor Stinnerea3183f2013-12-03 01:08:00 +0100147.. method:: BaseEventLoop.call_soon_threadsafe(callback, \*args)
148
149 Like :meth:`call_soon`, but thread safe.
150
151
Victor Stinner45b27ed2014-02-01 02:36:43 +0100152.. _asyncio-delayed-calls:
153
Victor Stinnerea3183f2013-12-03 01:08:00 +0100154Delayed calls
155-------------
156
157The event loop has its own internal clock for computing timeouts.
158Which clock is used depends on the (platform-specific) event loop
159implementation; ideally it is a monotonic clock. This will generally be
160a different clock than :func:`time.time`.
161
Victor Stinner8b21d912014-02-18 09:37:43 +0100162.. note::
163
164 Timeouts (relative *delay* or absolute *when*) should not exceed one day.
165
Victor Stinner45b27ed2014-02-01 02:36:43 +0100166
Victor Stinnerea3183f2013-12-03 01:08:00 +0100167.. method:: BaseEventLoop.call_later(delay, callback, *args)
168
169 Arrange for the *callback* to be called after the given *delay*
170 seconds (either an int or float).
171
Yury Selivanovd5797422014-02-19 20:58:44 -0500172 An instance of :class:`asyncio.Handle` is returned.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100173
174 *callback* will be called exactly once per call to :meth:`call_later`.
175 If two callbacks are scheduled for exactly the same time, it is
176 undefined which will be called first.
177
178 The optional positional *args* will be passed to the callback when it
179 is called. If you want the callback to be called with some named
180 arguments, use a closure or :func:`functools.partial`.
181
182.. method:: BaseEventLoop.call_at(when, callback, *args)
183
184 Arrange for the *callback* to be called at the given absolute timestamp
185 *when* (an int or float), using the same time reference as :meth:`time`.
186
187 This method's behavior is the same as :meth:`call_later`.
188
189.. method:: BaseEventLoop.time()
190
191 Return the current time, as a :class:`float` value, according to the
192 event loop's internal clock.
193
Victor Stinner3e09e322013-12-03 01:22:06 +0100194.. seealso::
195
196 The :func:`asyncio.sleep` function.
197
Victor Stinnerea3183f2013-12-03 01:08:00 +0100198
199Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100200--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100201
202.. 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)
203
204 Create a streaming transport connection to a given Internet *host* and
Victor Stinner03e9cb22014-02-19 13:32:34 +0100205 *port*: socket family :py:data:`~socket.AF_INET` or
206 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
207 socket type :py:data:`~socket.SOCK_STREAM`. *protocol_factory* must be a
208 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100209
Victor Stinner59759ff2014-01-16 19:30:21 +0100210 This method returns a :ref:`coroutine object <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100211 establish the connection in the background. When successful, the
212 coroutine returns a ``(transport, protocol)`` pair.
213
214 The chronological synopsis of the underlying operation is as follows:
215
Victor Stinner9592edb2014-02-02 15:03:02 +0100216 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100217 is created to represent it.
218
219 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100220 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100221
222 #. The protocol instance is tied to the transport, and its
223 :meth:`connection_made` method is called.
224
225 #. The coroutine returns successfully with the ``(transport, protocol)``
226 pair.
227
228 The created transport is an implementation-dependent bidirectional stream.
229
230 .. note::
231 *protocol_factory* can be any kind of callable, not necessarily
232 a class. For example, if you want to use a pre-created
233 protocol instance, you can pass ``lambda: my_protocol``.
234
235 Options allowing to change how the connection is created:
236
237 * *ssl*: if given and not false, a SSL/TLS transport is created
238 (by default a plain TCP transport is created). If *ssl* is
239 a :class:`ssl.SSLContext` object, this context is used to create
240 the transport; if *ssl* is :const:`True`, a context with some
241 unspecified default settings is used.
242
243 * *server_hostname*, is only for use together with *ssl*,
244 and sets or overrides the hostname that the target server's certificate
245 will be matched against. By default the value of the *host* argument
246 is used. If *host* is empty, there is no default and you must pass a
247 value for *server_hostname*. If *server_hostname* is an empty
248 string, hostname matching is disabled (which is a serious security
249 risk, allowing for man-in-the-middle-attacks).
250
251 * *family*, *proto*, *flags* are the optional address family, protocol
252 and flags to be passed through to getaddrinfo() for *host* resolution.
253 If given, these should all be integers from the corresponding
254 :mod:`socket` module constants.
255
256 * *sock*, if given, should be an existing, already connected
257 :class:`socket.socket` object to be used by the transport.
258 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
259 and *local_addr* should be specified.
260
261 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
262 to bind the socket to locally. The *local_host* and *local_port*
263 are looked up using getaddrinfo(), similarly to *host* and *port*.
264
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100265 .. seealso::
266
267 The :func:`open_connection` function can be used to get a pair of
268 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
269
Victor Stinnerea3183f2013-12-03 01:08:00 +0100270
Victor Stinner03e9cb22014-02-19 13:32:34 +0100271.. method:: BaseEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0)
272
273 Create datagram connection: socket family :py:data:`~socket.AF_INET` or
274 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
275 socket type :py:data:`~socket.SOCK_DGRAM`.
276
277 This method returns a :ref:`coroutine object <coroutine>` which will try to
278 establish the connection in the background. When successful, the
279 coroutine returns a ``(transport, protocol)`` pair.
280
281 See the :meth:`BaseEventLoop.create_connection` method for parameters.
282
283
284.. method:: BaseEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
285
286 Create UNIX connection: socket family :py:data:`~socket.AF_UNIX`, socket
287 type :py:data:`~socket.SOCK_STREAM`. The :py:data:`~socket.AF_UNIX` socket
288 family is used to communicate between processes on the same machine
289 efficiently.
290
291 This method returns a :ref:`coroutine object <coroutine>` which will try to
292 establish the connection in the background. When successful, the
293 coroutine returns a ``(transport, protocol)`` pair.
294
295 See the :meth:`BaseEventLoop.create_connection` method for parameters.
296
297 Availability: UNIX.
298
299
Victor Stinnerea3183f2013-12-03 01:08:00 +0100300Creating listening connections
301------------------------------
302
303.. 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)
304
Victor Stinner59759ff2014-01-16 19:30:21 +0100305 A :ref:`coroutine function <coroutine>` which creates a TCP server bound to host and
Victor Stinnerea3183f2013-12-03 01:08:00 +0100306 port.
307
308 The return value is a :class:`AbstractServer` object which can be used to stop
309 the service.
310
311 If *host* is an empty string or None all interfaces are assumed
312 and a list of multiple sockets will be returned (most likely
313 one for IPv4 and another one for IPv6).
314
315 *family* can be set to either :data:`~socket.AF_INET` or
316 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
317 it will be determined from host (defaults to :data:`~socket.AF_UNSPEC`).
318
319 *flags* is a bitmask for :meth:`getaddrinfo`.
320
321 *sock* can optionally be specified in order to use a preexisting
322 socket object.
323
324 *backlog* is the maximum number of queued connections passed to
325 :meth:`~socket.socket.listen` (defaults to 100).
326
327 ssl can be set to an :class:`~ssl.SSLContext` to enable SSL over the
328 accepted connections.
329
330 *reuse_address* tells the kernel to reuse a local socket in
331 TIME_WAIT state, without waiting for its natural timeout to
332 expire. If not specified will automatically be set to True on
333 UNIX.
334
Victor Stinner59759ff2014-01-16 19:30:21 +0100335 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100336
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100337 .. seealso::
338
339 The function :func:`start_server` creates a (:class:`StreamReader`,
340 :class:`StreamWriter`) pair and calls back a function with this pair.
341
Victor Stinnerea3183f2013-12-03 01:08:00 +0100342
Victor Stinner03e9cb22014-02-19 13:32:34 +0100343.. method:: BaseEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100344
Victor Stinner03e9cb22014-02-19 13:32:34 +0100345 Similar to :meth:`BaseEventLoop.create_server`, but specific to the
346 socket family :py:data:`~socket.AF_UNIX`.
347
348 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100349
350
351
Victor Stinnerc1567df2014-02-08 23:22:58 +0100352Watch file descriptors
353----------------------
354
355.. method:: BaseEventLoop.add_reader(fd, callback, \*args)
356
357 Start watching the file descriptor for read availability and then call the
358 *callback* with specified arguments.
359
360.. method:: BaseEventLoop.remove_reader(fd)
361
362 Stop watching the file descriptor for read availability.
363
364.. method:: BaseEventLoop.add_writer(fd, callback, \*args)
365
366 Start watching the file descriptor for write availability and then call the
367 *callback* with specified arguments.
368
369.. method:: BaseEventLoop.remove_writer(fd)
370
371 Stop watching the file descriptor for write availability.
372
373
374Low-level socket operations
375---------------------------
376
377.. method:: BaseEventLoop.sock_recv(sock, nbytes)
378
379 Receive data from the socket. The return value is a bytes object
380 representing the data received. The maximum amount of data to be received
381 at once is specified by *nbytes*.
382
383 This method returns a :ref:`coroutine object <coroutine>`.
384
385 .. seealso::
386
387 The :meth:`socket.socket.recv` method.
388
389.. method:: BaseEventLoop.sock_sendall(sock, data)
390
391 Send data to the socket. The socket must be connected to a remote socket.
392 This method continues to send data from *data* until either all data has
393 been sent or an error occurs. ``None`` is returned on success. On error,
394 an exception is raised, and there is no way to determine how much data, if
395 any, was successfully sent.
396
397 This method returns a :ref:`coroutine object <coroutine>`.
398
399 .. seealso::
400
401 The :meth:`socket.socket.sendall` method.
402
403.. method:: BaseEventLoop.sock_connect(sock, address)
404
405 Connect to a remote socket at *address*.
406
Victor Stinner28773462014-02-13 09:24:37 +0100407 The *address* must be already resolved to avoid the trap of hanging the
408 entire event loop when the address requires doing a DNS lookup. For
409 example, it must be an IP address, not an hostname, for
410 :py:data:`~socket.AF_INET` and :py:data:`~socket.AF_INET6` address families.
411 Use :meth:`getaddrinfo` to resolve the hostname asynchronously.
412
Victor Stinnerc1567df2014-02-08 23:22:58 +0100413 This method returns a :ref:`coroutine object <coroutine>`.
414
415 .. seealso::
416
417 The :meth:`BaseEventLoop.create_connection` method, the
418 :func:`open_connection` function and the :meth:`socket.socket.connect`
419 method.
420
421
422.. method:: BaseEventLoop.sock_accept(sock)
423
424 Accept a connection. The socket must be bound to an address and listening
425 for connections. The return value is a pair ``(conn, address)`` where *conn*
426 is a *new* socket object usable to send and receive data on the connection,
427 and *address* is the address bound to the socket on the other end of the
428 connection.
429
430 This method returns a :ref:`coroutine object <coroutine>`.
431
432 .. seealso::
433
434 The :meth:`BaseEventLoop.create_server` method, the :func:`start_server`
435 function and the :meth:`socket.socket.accept` method.
436
437
438Resolve host name
439-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100440
441.. method:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
442
Victor Stinnerc1567df2014-02-08 23:22:58 +0100443 Similar to the :meth:`socket.getaddrinfo` function, but return a
444 :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100445
446.. method:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
447
Victor Stinnerc1567df2014-02-08 23:22:58 +0100448 Similar to the :meth:`socket.getnameinfo` function, but return a
449 :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100450
451
452Running subprocesses
453--------------------
454
455Run subprocesses asynchronously using the :mod:`subprocess` module.
456
Victor Stinner041ff9b2014-01-28 02:24:22 +0100457.. note::
458
459 On Windows, the default event loop uses
460 :class:`selectors.SelectSelector` which only supports sockets. The
Victor Stinner45b27ed2014-02-01 02:36:43 +0100461 :class:`ProactorEventLoop` should be used to support subprocesses.
Victor Stinner041ff9b2014-01-28 02:24:22 +0100462
463.. note::
464
Ned Deilyeecbbad2014-01-27 19:03:07 -0700465 On Mac OS X older than 10.9 (Mavericks), :class:`selectors.KqueueSelector`
Victor Stinner041ff9b2014-01-28 02:24:22 +0100466 does not support character devices like PTY, whereas it is used by the
467 default event loop. The :class:`SelectorEventLoop` can be used with
Victor Stinner3bc647c2014-02-03 00:35:46 +0100468 :class:`SelectSelector` or :class:`PollSelector` to handle character devices
469 on Mac OS X 10.6 (Snow Leopard) and later.
Victor Stinner041ff9b2014-01-28 02:24:22 +0100470
Victor Stinnerea3183f2013-12-03 01:08:00 +0100471.. method:: BaseEventLoop.subprocess_exec(protocol_factory, \*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=False, shell=False, bufsize=0, \*\*kwargs)
472
473 XXX
474
Victor Stinner59759ff2014-01-16 19:30:21 +0100475 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100476
477 See the constructor of the :class:`subprocess.Popen` class for parameters.
478
479.. method:: BaseEventLoop.subprocess_shell(protocol_factory, cmd, \*, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=False, shell=True, bufsize=0, \*\*kwargs)
480
481 XXX
482
Victor Stinner59759ff2014-01-16 19:30:21 +0100483 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100484
485 See the constructor of the :class:`subprocess.Popen` class for parameters.
486
487.. method:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
488
489 Register read pipe in eventloop.
490
491 *protocol_factory* should instantiate object with :class:`Protocol`
492 interface. pipe is file-like object already switched to nonblocking.
493 Return pair (transport, protocol), where transport support
494 :class:`ReadTransport` interface.
495
Victor Stinner59759ff2014-01-16 19:30:21 +0100496 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100497
498.. method:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
499
500 Register write pipe in eventloop.
501
502 *protocol_factory* should instantiate object with :class:`BaseProtocol`
503 interface. Pipe is file-like object already switched to nonblocking.
504 Return pair (transport, protocol), where transport support
505 :class:`WriteTransport` interface.
506
Victor Stinner59759ff2014-01-16 19:30:21 +0100507 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100508
Victor Stinner08444382014-02-02 22:43:39 +0100509.. seealso::
510
511 The :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
512 functions.
513
Victor Stinnerea3183f2013-12-03 01:08:00 +0100514
Victor Stinner8b863482014-01-27 10:07:50 +0100515UNIX signals
516------------
517
518Availability: UNIX only.
519
520.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
521
522 Add a handler for a signal.
523
524 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
525 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
526
527.. method:: BaseEventLoop.remove_signal_handler(sig)
528
529 Remove a handler for a signal.
530
531 Return ``True`` if a signal handler was removed, ``False`` if not.
532
533.. seealso::
534
535 The :mod:`signal` module.
536
537
Victor Stinnerea3183f2013-12-03 01:08:00 +0100538Executor
539--------
540
541Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
542pool of processes). By default, an event loop uses a thread pool executor
543(:class:`~concurrent.futures.ThreadPoolExecutor`).
544
545.. method:: BaseEventLoop.run_in_executor(executor, callback, \*args)
546
547 Arrange for a callback to be called in the specified executor.
548
549 *executor* is a :class:`~concurrent.futures.Executor` instance,
550 the default executor is used if *executor* is ``None``.
551
552.. method:: BaseEventLoop.set_default_executor(executor)
553
554 Set the default executor used by :meth:`run_in_executor`.
555
556
Yury Selivanovd5797422014-02-19 20:58:44 -0500557Error Handling API
558------------------
559
560Allows to customize how exceptions are handled in the event loop.
561
562.. method:: BaseEventLoop.set_exception_handler(handler)
563
564 Set *handler* as the new event loop exception handler.
565
566 If *handler* is ``None``, the default exception handler will
567 be set.
568
569 If *handler* is a callable object, it should have a
570 matching signature to ``(loop, context)``, where ``loop``
571 will be a reference to the active event loop, ``context``
572 will be a ``dict`` object (see :meth:`call_exception_handler`
573 documentation for details about context).
574
575.. method:: BaseEventLoop.default_exception_handler(context)
576
577 Default exception handler.
578
579 This is called when an exception occurs and no exception
580 handler is set, and can be called by a custom exception
581 handler that wants to defer to the default behavior.
582
583 *context* parameter has the same meaning as in
584 :meth:`call_exception_handler`.
585
586.. method:: BaseEventLoop.call_exception_handler(context)
587
588 Call the current event loop exception handler.
589
590 *context* is a ``dict`` object containing the following keys
591 (new keys may be introduced later):
592
593 * 'message': Error message;
594 * 'exception' (optional): Exception object;
595 * 'future' (optional): :class:`asyncio.Future` instance;
596 * 'handle' (optional): :class:`asyncio.Handle` instance;
597 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
598 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
599 * 'socket' (optional): :class:`socket.socket` instance.
600
601 .. note::
602
603 Note: this method should not be overloaded in subclassed
604 event loops. For any custom exception handling, use
605 :meth:`set_exception_handler()` method.
606
Victor Stinner7ef60cd2014-02-19 23:15:02 +0100607Debug mode
608----------
609
610.. method:: BaseEventLoop.get_debug()
611
Victor Stinneraabc1312014-02-20 01:44:10 +0100612 Get the debug mode (:class:`bool`) of the event loop, ``False`` by default.
Victor Stinner7ef60cd2014-02-19 23:15:02 +0100613
614.. method:: BaseEventLoop.set_debug(enabled: bool)
615
616 Set the debug mode of the event loop.
617
618.. seealso::
619
620 The :ref:`Develop with asyncio <asyncio-dev>` section.
621
622
Victor Stinner8c462c52014-01-24 18:11:43 +0100623Server
624------
625
626.. class:: AbstractServer
627
628 Abstract server returned by :func:`BaseEventLoop.create_server`.
629
630 .. method:: close()
631
632 Stop serving. This leaves existing connections open.
633
634 .. method:: wait_closed()
635
636 Coroutine to wait until service is closed.
637
638
Yury Selivanovd5797422014-02-19 20:58:44 -0500639Handle
640------
641
642.. class:: Handle
643
644 A callback wrapper object returned by :func:`BaseEventLoop.call_soon`,
645 :func:`BaseEventLoop.call_soon_threadsafe`, :func:`BaseEventLoop.call_later`,
646 and :func:`BaseEventLoop.call_at`.
647
648 .. method:: cancel()
649
650 Cancel the call.
651
652
Victor Stinner3e09e322013-12-03 01:22:06 +0100653.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100654
Victor Stinner3e09e322013-12-03 01:22:06 +0100655Example: Hello World (callback)
656-------------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100657
658Print ``Hello World`` every two seconds, using a callback::
659
660 import asyncio
661
662 def print_and_repeat(loop):
663 print('Hello World')
664 loop.call_later(2, print_and_repeat, loop)
665
666 loop = asyncio.get_event_loop()
Victor Stinnerdbd89502013-12-10 02:47:22 +0100667 loop.call_soon(print_and_repeat, loop)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100668 loop.run_forever()
669
Victor Stinner3e09e322013-12-03 01:22:06 +0100670.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100671
Victor Stinner3e09e322013-12-03 01:22:06 +0100672 :ref:`Hello World example using a coroutine <asyncio-hello-world-coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100673
Victor Stinner8b863482014-01-27 10:07:50 +0100674
675Example: Set signal handlers for SIGINT and SIGTERM
676---------------------------------------------------
677
678Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`::
679
680 import asyncio
681 import functools
682 import os
683 import signal
684
685 def ask_exit(signame):
686 print("got signal %s: exit" % signame)
687 loop.stop()
688
689 loop = asyncio.get_event_loop()
690 for signame in ('SIGINT', 'SIGTERM'):
691 loop.add_signal_handler(getattr(signal, signame),
692 functools.partial(ask_exit, signame))
693
694 print("Event loop running forever, press CTRL+c to interrupt.")
695 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
696 loop.run_forever()
697