blob: c242fc3dc1b3f452cad8d775f18178f5fd6f8897 [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
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200135 The event loop must not be running.
136
Victor Stinnerea3183f2013-12-03 01:08:00 +0100137 This is idempotent and irreversible. No other methods should be called after
138 this one.
139
140
141Calls
142-----
143
144.. method:: BaseEventLoop.call_soon(callback, \*args)
145
146 Arrange for a callback to be called as soon as possible.
147
148 This operates as a FIFO queue, callbacks are called in the order in
149 which they are registered. Each callback will be called exactly once.
150
151 Any positional arguments after the callback will be passed to the
152 callback when it is called.
153
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500154 An instance of :class:`asyncio.Handle` is returned.
155
Victor Stinnerea3183f2013-12-03 01:08:00 +0100156.. method:: BaseEventLoop.call_soon_threadsafe(callback, \*args)
157
158 Like :meth:`call_soon`, but thread safe.
159
160
Victor Stinner45b27ed2014-02-01 02:36:43 +0100161.. _asyncio-delayed-calls:
162
Victor Stinnerea3183f2013-12-03 01:08:00 +0100163Delayed calls
164-------------
165
166The event loop has its own internal clock for computing timeouts.
167Which clock is used depends on the (platform-specific) event loop
168implementation; ideally it is a monotonic clock. This will generally be
169a different clock than :func:`time.time`.
170
Victor Stinnerfd9d3742014-02-18 09:37:43 +0100171.. note::
172
173 Timeouts (relative *delay* or absolute *when*) should not exceed one day.
174
Victor Stinner45b27ed2014-02-01 02:36:43 +0100175
Victor Stinnerea3183f2013-12-03 01:08:00 +0100176.. method:: BaseEventLoop.call_later(delay, callback, *args)
177
178 Arrange for the *callback* to be called after the given *delay*
179 seconds (either an int or float).
180
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500181 An instance of :class:`asyncio.Handle` is returned.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100182
183 *callback* will be called exactly once per call to :meth:`call_later`.
184 If two callbacks are scheduled for exactly the same time, it is
185 undefined which will be called first.
186
187 The optional positional *args* will be passed to the callback when it
188 is called. If you want the callback to be called with some named
189 arguments, use a closure or :func:`functools.partial`.
190
191.. method:: BaseEventLoop.call_at(when, callback, *args)
192
193 Arrange for the *callback* to be called at the given absolute timestamp
194 *when* (an int or float), using the same time reference as :meth:`time`.
195
196 This method's behavior is the same as :meth:`call_later`.
197
198.. method:: BaseEventLoop.time()
199
200 Return the current time, as a :class:`float` value, according to the
201 event loop's internal clock.
202
Victor Stinner3e09e322013-12-03 01:22:06 +0100203.. seealso::
204
205 The :func:`asyncio.sleep` function.
206
Victor Stinnerea3183f2013-12-03 01:08:00 +0100207
208Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100209--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100210
211.. 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)
212
213 Create a streaming transport connection to a given Internet *host* and
Victor Stinnera6919aa2014-02-19 13:32:34 +0100214 *port*: socket family :py:data:`~socket.AF_INET` or
215 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
216 socket type :py:data:`~socket.SOCK_STREAM`. *protocol_factory* must be a
217 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100218
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500219 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100220 establish the connection in the background. When successful, the
221 coroutine returns a ``(transport, protocol)`` pair.
222
223 The chronological synopsis of the underlying operation is as follows:
224
Victor Stinner9592edb2014-02-02 15:03:02 +0100225 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100226 is created to represent it.
227
228 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100229 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100230
231 #. The protocol instance is tied to the transport, and its
232 :meth:`connection_made` method is called.
233
234 #. The coroutine returns successfully with the ``(transport, protocol)``
235 pair.
236
237 The created transport is an implementation-dependent bidirectional stream.
238
239 .. note::
240 *protocol_factory* can be any kind of callable, not necessarily
241 a class. For example, if you want to use a pre-created
242 protocol instance, you can pass ``lambda: my_protocol``.
243
244 Options allowing to change how the connection is created:
245
246 * *ssl*: if given and not false, a SSL/TLS transport is created
247 (by default a plain TCP transport is created). If *ssl* is
248 a :class:`ssl.SSLContext` object, this context is used to create
249 the transport; if *ssl* is :const:`True`, a context with some
250 unspecified default settings is used.
251
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100252 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
253
Victor Stinnerea3183f2013-12-03 01:08:00 +0100254 * *server_hostname*, is only for use together with *ssl*,
255 and sets or overrides the hostname that the target server's certificate
256 will be matched against. By default the value of the *host* argument
257 is used. If *host* is empty, there is no default and you must pass a
258 value for *server_hostname*. If *server_hostname* is an empty
259 string, hostname matching is disabled (which is a serious security
260 risk, allowing for man-in-the-middle-attacks).
261
262 * *family*, *proto*, *flags* are the optional address family, protocol
263 and flags to be passed through to getaddrinfo() for *host* resolution.
264 If given, these should all be integers from the corresponding
265 :mod:`socket` module constants.
266
267 * *sock*, if given, should be an existing, already connected
268 :class:`socket.socket` object to be used by the transport.
269 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
270 and *local_addr* should be specified.
271
272 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
273 to bind the socket to locally. The *local_host* and *local_port*
274 are looked up using getaddrinfo(), similarly to *host* and *port*.
275
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100276 .. seealso::
277
278 The :func:`open_connection` function can be used to get a pair of
279 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
280
Victor Stinnerea3183f2013-12-03 01:08:00 +0100281
Victor Stinnera6919aa2014-02-19 13:32:34 +0100282.. method:: BaseEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0)
283
284 Create datagram connection: socket family :py:data:`~socket.AF_INET` or
285 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
286 socket type :py:data:`~socket.SOCK_DGRAM`.
287
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500288 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100289 establish the connection in the background. When successful, the
290 coroutine returns a ``(transport, protocol)`` pair.
291
292 See the :meth:`BaseEventLoop.create_connection` method for parameters.
293
294
295.. method:: BaseEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
296
297 Create UNIX connection: socket family :py:data:`~socket.AF_UNIX`, socket
298 type :py:data:`~socket.SOCK_STREAM`. The :py:data:`~socket.AF_UNIX` socket
299 family is used to communicate between processes on the same machine
300 efficiently.
301
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500302 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100303 establish the connection in the background. When successful, the
304 coroutine returns a ``(transport, protocol)`` pair.
305
306 See the :meth:`BaseEventLoop.create_connection` method for parameters.
307
308 Availability: UNIX.
309
310
Victor Stinnerea3183f2013-12-03 01:08:00 +0100311Creating listening connections
312------------------------------
313
314.. 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)
315
Victor Stinnerd1432092014-06-19 17:11:49 +0200316 Create a TCP server bound to host and port. Return an
317 :class:`AbstractServer` object which can be used to stop the service.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100318
Victor Stinnerd1432092014-06-19 17:11:49 +0200319 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100320
321 If *host* is an empty string or None all interfaces are assumed
322 and a list of multiple sockets will be returned (most likely
323 one for IPv4 and another one for IPv6).
324
325 *family* can be set to either :data:`~socket.AF_INET` or
326 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
327 it will be determined from host (defaults to :data:`~socket.AF_UNSPEC`).
328
329 *flags* is a bitmask for :meth:`getaddrinfo`.
330
331 *sock* can optionally be specified in order to use a preexisting
332 socket object.
333
334 *backlog* is the maximum number of queued connections passed to
335 :meth:`~socket.socket.listen` (defaults to 100).
336
337 ssl can be set to an :class:`~ssl.SSLContext` to enable SSL over the
338 accepted connections.
339
340 *reuse_address* tells the kernel to reuse a local socket in
341 TIME_WAIT state, without waiting for its natural timeout to
342 expire. If not specified will automatically be set to True on
343 UNIX.
344
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100345 .. seealso::
346
347 The function :func:`start_server` creates a (:class:`StreamReader`,
348 :class:`StreamWriter`) pair and calls back a function with this pair.
349
Victor Stinnerea3183f2013-12-03 01:08:00 +0100350
Victor Stinnera6919aa2014-02-19 13:32:34 +0100351.. method:: BaseEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100352
Victor Stinnera6919aa2014-02-19 13:32:34 +0100353 Similar to :meth:`BaseEventLoop.create_server`, but specific to the
354 socket family :py:data:`~socket.AF_UNIX`.
355
356 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100357
358
359
Victor Stinnerc1567df2014-02-08 23:22:58 +0100360Watch file descriptors
361----------------------
362
363.. method:: BaseEventLoop.add_reader(fd, callback, \*args)
364
365 Start watching the file descriptor for read availability and then call the
366 *callback* with specified arguments.
367
368.. method:: BaseEventLoop.remove_reader(fd)
369
370 Stop watching the file descriptor for read availability.
371
372.. method:: BaseEventLoop.add_writer(fd, callback, \*args)
373
374 Start watching the file descriptor for write availability and then call the
375 *callback* with specified arguments.
376
377.. method:: BaseEventLoop.remove_writer(fd)
378
379 Stop watching the file descriptor for write availability.
380
381
382Low-level socket operations
383---------------------------
384
385.. method:: BaseEventLoop.sock_recv(sock, nbytes)
386
387 Receive data from the socket. The return value is a bytes object
388 representing the data received. The maximum amount of data to be received
389 at once is specified by *nbytes*.
390
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:`socket.socket.recv` method.
396
397.. method:: BaseEventLoop.sock_sendall(sock, data)
398
399 Send data to the socket. The socket must be connected to a remote socket.
400 This method continues to send data from *data* until either all data has
401 been sent or an error occurs. ``None`` is returned on success. On error,
402 an exception is raised, and there is no way to determine how much data, if
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500403 any, was successfully processed by the receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100404
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500405 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100406
407 .. seealso::
408
409 The :meth:`socket.socket.sendall` method.
410
411.. method:: BaseEventLoop.sock_connect(sock, address)
412
413 Connect to a remote socket at *address*.
414
Victor Stinner1b0580b2014-02-13 09:24:37 +0100415 The *address* must be already resolved to avoid the trap of hanging the
416 entire event loop when the address requires doing a DNS lookup. For
417 example, it must be an IP address, not an hostname, for
418 :py:data:`~socket.AF_INET` and :py:data:`~socket.AF_INET6` address families.
419 Use :meth:`getaddrinfo` to resolve the hostname asynchronously.
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_connection` method, the
426 :func:`open_connection` function and the :meth:`socket.socket.connect`
427 method.
428
429
430.. method:: BaseEventLoop.sock_accept(sock)
431
432 Accept a connection. The socket must be bound to an address and listening
433 for connections. The return value is a pair ``(conn, address)`` where *conn*
434 is a *new* socket object usable to send and receive data on the connection,
435 and *address* is the address bound to the socket on the other end of the
436 connection.
437
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500438 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100439
440 .. seealso::
441
442 The :meth:`BaseEventLoop.create_server` method, the :func:`start_server`
443 function and the :meth:`socket.socket.accept` method.
444
445
446Resolve host name
447-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100448
449.. method:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
450
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500451 This method is a :ref:`coroutine <coroutine>`, similar to
452 :meth:`socket.getaddrinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100453
454.. method:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
455
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500456 This method is a :ref:`coroutine <coroutine>`, similar to
457 :meth:`socket.getnameinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100458
459
Victor Stinner984600f2014-03-25 09:40:26 +0100460Connect pipes
461-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100462
463.. method:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
464
Victor Stinnera5b257a2014-05-29 00:14:03 +0200465 Register read pipe in eventloop. Set the *pipe* to non-blocking mode.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100466
467 *protocol_factory* should instantiate object with :class:`Protocol`
Victor Stinnera5b257a2014-05-29 00:14:03 +0200468 interface. *pipe* is a :term:`file-like object <file object>`.
469 Return pair ``(transport, protocol)``, where *transport* supports the
Victor Stinnerea3183f2013-12-03 01:08:00 +0100470 :class:`ReadTransport` interface.
471
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500472 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100473
474.. method:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
475
476 Register write pipe in eventloop.
477
478 *protocol_factory* should instantiate object with :class:`BaseProtocol`
479 interface. Pipe is file-like object already switched to nonblocking.
480 Return pair (transport, protocol), where transport support
481 :class:`WriteTransport` interface.
482
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500483 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100484
Victor Stinner08444382014-02-02 22:43:39 +0100485.. seealso::
486
Victor Stinner984600f2014-03-25 09:40:26 +0100487 The :meth:`BaseEventLoop.subprocess_exec` and
488 :meth:`BaseEventLoop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100489
Victor Stinnerea3183f2013-12-03 01:08:00 +0100490
Victor Stinner8b863482014-01-27 10:07:50 +0100491UNIX signals
492------------
493
494Availability: UNIX only.
495
496.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
497
498 Add a handler for a signal.
499
500 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
501 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
502
503.. method:: BaseEventLoop.remove_signal_handler(sig)
504
505 Remove a handler for a signal.
506
507 Return ``True`` if a signal handler was removed, ``False`` if not.
508
509.. seealso::
510
511 The :mod:`signal` module.
512
513
Victor Stinnerea3183f2013-12-03 01:08:00 +0100514Executor
515--------
516
517Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
518pool of processes). By default, an event loop uses a thread pool executor
519(:class:`~concurrent.futures.ThreadPoolExecutor`).
520
521.. method:: BaseEventLoop.run_in_executor(executor, callback, \*args)
522
523 Arrange for a callback to be called in the specified executor.
524
Larry Hastings3732ed22014-03-15 21:13:56 -0700525 The *executor* argument should be an :class:`~concurrent.futures.Executor`
526 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100527
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500528 This method is a :ref:`coroutine <coroutine>`.
529
Victor Stinnerea3183f2013-12-03 01:08:00 +0100530.. method:: BaseEventLoop.set_default_executor(executor)
531
532 Set the default executor used by :meth:`run_in_executor`.
533
534
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500535Error Handling API
536------------------
537
538Allows to customize how exceptions are handled in the event loop.
539
540.. method:: BaseEventLoop.set_exception_handler(handler)
541
542 Set *handler* as the new event loop exception handler.
543
544 If *handler* is ``None``, the default exception handler will
545 be set.
546
547 If *handler* is a callable object, it should have a
548 matching signature to ``(loop, context)``, where ``loop``
549 will be a reference to the active event loop, ``context``
550 will be a ``dict`` object (see :meth:`call_exception_handler`
551 documentation for details about context).
552
553.. method:: BaseEventLoop.default_exception_handler(context)
554
555 Default exception handler.
556
557 This is called when an exception occurs and no exception
558 handler is set, and can be called by a custom exception
559 handler that wants to defer to the default behavior.
560
561 *context* parameter has the same meaning as in
562 :meth:`call_exception_handler`.
563
564.. method:: BaseEventLoop.call_exception_handler(context)
565
566 Call the current event loop exception handler.
567
568 *context* is a ``dict`` object containing the following keys
569 (new keys may be introduced later):
570
571 * 'message': Error message;
572 * 'exception' (optional): Exception object;
573 * 'future' (optional): :class:`asyncio.Future` instance;
574 * 'handle' (optional): :class:`asyncio.Handle` instance;
575 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
576 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
577 * 'socket' (optional): :class:`socket.socket` instance.
578
579 .. note::
580
581 Note: this method should not be overloaded in subclassed
582 event loops. For any custom exception handling, use
583 :meth:`set_exception_handler()` method.
584
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100585Debug mode
586----------
587
588.. method:: BaseEventLoop.get_debug()
589
Victor Stinner7b7120e2014-06-23 00:12:14 +0200590 Get the debug mode (:class:`bool`) of the event loop.
591
592 The default value is ``True`` if the environment variable
593 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
594 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100595
Victor Stinner64d750b2014-06-18 03:25:23 +0200596 .. versionadded:: 3.4.2
597
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100598.. method:: BaseEventLoop.set_debug(enabled: bool)
599
600 Set the debug mode of the event loop.
601
Victor Stinner64d750b2014-06-18 03:25:23 +0200602 .. versionadded:: 3.4.2
603
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100604.. seealso::
605
Victor Stinner62511fd2014-06-23 00:36:11 +0200606 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100607
608
Victor Stinner8c462c52014-01-24 18:11:43 +0100609Server
610------
611
612.. class:: AbstractServer
613
614 Abstract server returned by :func:`BaseEventLoop.create_server`.
615
616 .. method:: close()
617
618 Stop serving. This leaves existing connections open.
619
620 .. method:: wait_closed()
621
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500622 A :ref:`coroutine <coroutine>` to wait until service is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100623
624
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500625Handle
626------
627
628.. class:: Handle
629
630 A callback wrapper object returned by :func:`BaseEventLoop.call_soon`,
631 :func:`BaseEventLoop.call_soon_threadsafe`, :func:`BaseEventLoop.call_later`,
632 and :func:`BaseEventLoop.call_at`.
633
634 .. method:: cancel()
635
636 Cancel the call.
637
638
Victor Stinner3e09e322013-12-03 01:22:06 +0100639.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100640
Victor Stinner3e09e322013-12-03 01:22:06 +0100641Example: Hello World (callback)
642-------------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100643
644Print ``Hello World`` every two seconds, using a callback::
645
646 import asyncio
647
648 def print_and_repeat(loop):
649 print('Hello World')
650 loop.call_later(2, print_and_repeat, loop)
651
652 loop = asyncio.get_event_loop()
Victor Stinnerdbd89502013-12-10 02:47:22 +0100653 loop.call_soon(print_and_repeat, loop)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100654 loop.run_forever()
655
Victor Stinner3e09e322013-12-03 01:22:06 +0100656.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100657
Victor Stinner3e09e322013-12-03 01:22:06 +0100658 :ref:`Hello World example using a coroutine <asyncio-hello-world-coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100659
Victor Stinner8b863482014-01-27 10:07:50 +0100660
661Example: Set signal handlers for SIGINT and SIGTERM
662---------------------------------------------------
663
664Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`::
665
666 import asyncio
667 import functools
668 import os
669 import signal
670
671 def ask_exit(signame):
672 print("got signal %s: exit" % signame)
673 loop.stop()
674
675 loop = asyncio.get_event_loop()
676 for signame in ('SIGINT', 'SIGTERM'):
677 loop.add_signal_handler(getattr(signal, signame),
678 functools.partial(ask_exit, signame))
679
680 print("Event loop running forever, press CTRL+c to interrupt.")
681 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
682 loop.run_forever()
683