blob: 1e16b9e6546abd32d241c825e3e2cad5929a46ea [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
150 .. seealso::
151
152 The :meth:`async` function.
153
154 .. versionadded:: 3.4.2
155
156
Victor Stinnerea3183f2013-12-03 01:08:00 +0100157Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100158--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100159
160.. 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)
161
162 Create a streaming transport connection to a given Internet *host* and
Victor Stinnera6919aa2014-02-19 13:32:34 +0100163 *port*: socket family :py:data:`~socket.AF_INET` or
164 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
165 socket type :py:data:`~socket.SOCK_STREAM`. *protocol_factory* must be a
166 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100167
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500168 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100169 establish the connection in the background. When successful, the
170 coroutine returns a ``(transport, protocol)`` pair.
171
172 The chronological synopsis of the underlying operation is as follows:
173
Victor Stinner9592edb2014-02-02 15:03:02 +0100174 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100175 is created to represent it.
176
177 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100178 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100179
180 #. The protocol instance is tied to the transport, and its
181 :meth:`connection_made` method is called.
182
183 #. The coroutine returns successfully with the ``(transport, protocol)``
184 pair.
185
186 The created transport is an implementation-dependent bidirectional stream.
187
188 .. note::
189 *protocol_factory* can be any kind of callable, not necessarily
190 a class. For example, if you want to use a pre-created
191 protocol instance, you can pass ``lambda: my_protocol``.
192
193 Options allowing to change how the connection is created:
194
195 * *ssl*: if given and not false, a SSL/TLS transport is created
196 (by default a plain TCP transport is created). If *ssl* is
197 a :class:`ssl.SSLContext` object, this context is used to create
198 the transport; if *ssl* is :const:`True`, a context with some
199 unspecified default settings is used.
200
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100201 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
202
Victor Stinnerea3183f2013-12-03 01:08:00 +0100203 * *server_hostname*, is only for use together with *ssl*,
204 and sets or overrides the hostname that the target server's certificate
205 will be matched against. By default the value of the *host* argument
206 is used. If *host* is empty, there is no default and you must pass a
207 value for *server_hostname*. If *server_hostname* is an empty
208 string, hostname matching is disabled (which is a serious security
209 risk, allowing for man-in-the-middle-attacks).
210
211 * *family*, *proto*, *flags* are the optional address family, protocol
212 and flags to be passed through to getaddrinfo() for *host* resolution.
213 If given, these should all be integers from the corresponding
214 :mod:`socket` module constants.
215
216 * *sock*, if given, should be an existing, already connected
217 :class:`socket.socket` object to be used by the transport.
218 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
219 and *local_addr* should be specified.
220
221 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
222 to bind the socket to locally. The *local_host* and *local_port*
223 are looked up using getaddrinfo(), similarly to *host* and *port*.
224
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100225 .. seealso::
226
227 The :func:`open_connection` function can be used to get a pair of
228 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
229
Victor Stinnerea3183f2013-12-03 01:08:00 +0100230
Victor Stinnera6919aa2014-02-19 13:32:34 +0100231.. method:: BaseEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0)
232
233 Create datagram connection: socket family :py:data:`~socket.AF_INET` or
234 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
235 socket type :py:data:`~socket.SOCK_DGRAM`.
236
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500237 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100238 establish the connection in the background. When successful, the
239 coroutine returns a ``(transport, protocol)`` pair.
240
241 See the :meth:`BaseEventLoop.create_connection` method for parameters.
242
243
244.. method:: BaseEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
245
246 Create UNIX connection: socket family :py:data:`~socket.AF_UNIX`, socket
247 type :py:data:`~socket.SOCK_STREAM`. The :py:data:`~socket.AF_UNIX` socket
248 family is used to communicate between processes on the same machine
249 efficiently.
250
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500251 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100252 establish the connection in the background. When successful, the
253 coroutine returns a ``(transport, protocol)`` pair.
254
255 See the :meth:`BaseEventLoop.create_connection` method for parameters.
256
257 Availability: UNIX.
258
259
Victor Stinnerea3183f2013-12-03 01:08:00 +0100260Creating listening connections
261------------------------------
262
263.. 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)
264
Victor Stinner8ebeb032014-07-11 23:47:40 +0200265 Create a TCP server bound to host and port. Return a :class:`Server` object,
266 its :attr:`~Server.sockets` attribute contains created sockets. Use the
267 :meth:`Server.close` method to stop the server: close listening sockets.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100268
Victor Stinnerd1432092014-06-19 17:11:49 +0200269 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100270
271 If *host* is an empty string or None all interfaces are assumed
272 and a list of multiple sockets will be returned (most likely
273 one for IPv4 and another one for IPv6).
274
275 *family* can be set to either :data:`~socket.AF_INET` or
276 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
277 it will be determined from host (defaults to :data:`~socket.AF_UNSPEC`).
278
279 *flags* is a bitmask for :meth:`getaddrinfo`.
280
281 *sock* can optionally be specified in order to use a preexisting
282 socket object.
283
284 *backlog* is the maximum number of queued connections passed to
285 :meth:`~socket.socket.listen` (defaults to 100).
286
287 ssl can be set to an :class:`~ssl.SSLContext` to enable SSL over the
288 accepted connections.
289
290 *reuse_address* tells the kernel to reuse a local socket in
291 TIME_WAIT state, without waiting for its natural timeout to
292 expire. If not specified will automatically be set to True on
293 UNIX.
294
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100295 .. seealso::
296
297 The function :func:`start_server` creates a (:class:`StreamReader`,
298 :class:`StreamWriter`) pair and calls back a function with this pair.
299
Victor Stinnerea3183f2013-12-03 01:08:00 +0100300
Victor Stinnera6919aa2014-02-19 13:32:34 +0100301.. method:: BaseEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100302
Victor Stinnera6919aa2014-02-19 13:32:34 +0100303 Similar to :meth:`BaseEventLoop.create_server`, but specific to the
304 socket family :py:data:`~socket.AF_UNIX`.
305
306 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100307
308
Victor Stinnerc1567df2014-02-08 23:22:58 +0100309Watch file descriptors
310----------------------
311
312.. method:: BaseEventLoop.add_reader(fd, callback, \*args)
313
314 Start watching the file descriptor for read availability and then call the
315 *callback* with specified arguments.
316
317.. method:: BaseEventLoop.remove_reader(fd)
318
319 Stop watching the file descriptor for read availability.
320
321.. method:: BaseEventLoop.add_writer(fd, callback, \*args)
322
323 Start watching the file descriptor for write availability and then call the
324 *callback* with specified arguments.
325
326.. method:: BaseEventLoop.remove_writer(fd)
327
328 Stop watching the file descriptor for write availability.
329
330
331Low-level socket operations
332---------------------------
333
334.. method:: BaseEventLoop.sock_recv(sock, nbytes)
335
336 Receive data from the socket. The return value is a bytes object
337 representing the data received. The maximum amount of data to be received
338 at once is specified by *nbytes*.
339
Victor Stinnerec2ce092014-07-29 23:12:22 +0200340 The socket *sock* must be non-blocking.
341
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500342 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100343
344 .. seealso::
345
346 The :meth:`socket.socket.recv` method.
347
348.. method:: BaseEventLoop.sock_sendall(sock, data)
349
350 Send data to the socket. The socket must be connected to a remote socket.
351 This method continues to send data from *data* until either all data has
352 been sent or an error occurs. ``None`` is returned on success. On error,
353 an exception is raised, and there is no way to determine how much data, if
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500354 any, was successfully processed by the receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100355
Victor Stinnerec2ce092014-07-29 23:12:22 +0200356 The socket *sock* must be non-blocking.
357
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500358 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100359
360 .. seealso::
361
362 The :meth:`socket.socket.sendall` method.
363
364.. method:: BaseEventLoop.sock_connect(sock, address)
365
366 Connect to a remote socket at *address*.
367
Victor Stinner1b0580b2014-02-13 09:24:37 +0100368 The *address* must be already resolved to avoid the trap of hanging the
369 entire event loop when the address requires doing a DNS lookup. For
370 example, it must be an IP address, not an hostname, for
371 :py:data:`~socket.AF_INET` and :py:data:`~socket.AF_INET6` address families.
372 Use :meth:`getaddrinfo` to resolve the hostname asynchronously.
373
Victor Stinnerec2ce092014-07-29 23:12:22 +0200374 The socket *sock* must be non-blocking.
375
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500376 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100377
378 .. seealso::
379
380 The :meth:`BaseEventLoop.create_connection` method, the
381 :func:`open_connection` function and the :meth:`socket.socket.connect`
382 method.
383
384
385.. method:: BaseEventLoop.sock_accept(sock)
386
387 Accept a connection. The socket must be bound to an address and listening
388 for connections. The return value is a pair ``(conn, address)`` where *conn*
389 is a *new* socket object usable to send and receive data on the connection,
390 and *address* is the address bound to the socket on the other end of the
391 connection.
392
Victor Stinnerec2ce092014-07-29 23:12:22 +0200393 The socket *sock* must be non-blocking.
394
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500395 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100396
397 .. seealso::
398
399 The :meth:`BaseEventLoop.create_server` method, the :func:`start_server`
400 function and the :meth:`socket.socket.accept` method.
401
402
403Resolve host name
404-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100405
406.. method:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
407
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500408 This method is a :ref:`coroutine <coroutine>`, similar to
409 :meth:`socket.getaddrinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100410
411.. method:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
412
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500413 This method is a :ref:`coroutine <coroutine>`, similar to
414 :meth:`socket.getnameinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100415
416
Victor Stinner984600f2014-03-25 09:40:26 +0100417Connect pipes
418-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100419
420.. method:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
421
Victor Stinnera5b257a2014-05-29 00:14:03 +0200422 Register read pipe in eventloop. Set the *pipe* to non-blocking mode.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100423
424 *protocol_factory* should instantiate object with :class:`Protocol`
Victor Stinnera5b257a2014-05-29 00:14:03 +0200425 interface. *pipe* is a :term:`file-like object <file object>`.
426 Return pair ``(transport, protocol)``, where *transport* supports the
Victor Stinnerea3183f2013-12-03 01:08:00 +0100427 :class:`ReadTransport` interface.
428
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500429 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100430
431.. method:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
432
433 Register write pipe in eventloop.
434
435 *protocol_factory* should instantiate object with :class:`BaseProtocol`
436 interface. Pipe is file-like object already switched to nonblocking.
437 Return pair (transport, protocol), where transport support
438 :class:`WriteTransport` interface.
439
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500440 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100441
Victor Stinner08444382014-02-02 22:43:39 +0100442.. seealso::
443
Victor Stinner984600f2014-03-25 09:40:26 +0100444 The :meth:`BaseEventLoop.subprocess_exec` and
445 :meth:`BaseEventLoop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100446
Victor Stinnerea3183f2013-12-03 01:08:00 +0100447
Victor Stinner8b863482014-01-27 10:07:50 +0100448UNIX signals
449------------
450
451Availability: UNIX only.
452
453.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
454
455 Add a handler for a signal.
456
457 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
458 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
459
460.. method:: BaseEventLoop.remove_signal_handler(sig)
461
462 Remove a handler for a signal.
463
464 Return ``True`` if a signal handler was removed, ``False`` if not.
465
466.. seealso::
467
468 The :mod:`signal` module.
469
470
Victor Stinnerea3183f2013-12-03 01:08:00 +0100471Executor
472--------
473
474Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
475pool of processes). By default, an event loop uses a thread pool executor
476(:class:`~concurrent.futures.ThreadPoolExecutor`).
477
478.. method:: BaseEventLoop.run_in_executor(executor, callback, \*args)
479
480 Arrange for a callback to be called in the specified executor.
481
Larry Hastings3732ed22014-03-15 21:13:56 -0700482 The *executor* argument should be an :class:`~concurrent.futures.Executor`
483 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100484
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500485 This method is a :ref:`coroutine <coroutine>`.
486
Victor Stinnerea3183f2013-12-03 01:08:00 +0100487.. method:: BaseEventLoop.set_default_executor(executor)
488
489 Set the default executor used by :meth:`run_in_executor`.
490
491
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500492Error Handling API
493------------------
494
495Allows to customize how exceptions are handled in the event loop.
496
497.. method:: BaseEventLoop.set_exception_handler(handler)
498
499 Set *handler* as the new event loop exception handler.
500
501 If *handler* is ``None``, the default exception handler will
502 be set.
503
504 If *handler* is a callable object, it should have a
505 matching signature to ``(loop, context)``, where ``loop``
506 will be a reference to the active event loop, ``context``
507 will be a ``dict`` object (see :meth:`call_exception_handler`
508 documentation for details about context).
509
510.. method:: BaseEventLoop.default_exception_handler(context)
511
512 Default exception handler.
513
514 This is called when an exception occurs and no exception
515 handler is set, and can be called by a custom exception
516 handler that wants to defer to the default behavior.
517
518 *context* parameter has the same meaning as in
519 :meth:`call_exception_handler`.
520
521.. method:: BaseEventLoop.call_exception_handler(context)
522
523 Call the current event loop exception handler.
524
525 *context* is a ``dict`` object containing the following keys
526 (new keys may be introduced later):
527
528 * 'message': Error message;
529 * 'exception' (optional): Exception object;
530 * 'future' (optional): :class:`asyncio.Future` instance;
531 * 'handle' (optional): :class:`asyncio.Handle` instance;
532 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
533 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
534 * 'socket' (optional): :class:`socket.socket` instance.
535
536 .. note::
537
538 Note: this method should not be overloaded in subclassed
539 event loops. For any custom exception handling, use
540 :meth:`set_exception_handler()` method.
541
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100542Debug mode
543----------
544
545.. method:: BaseEventLoop.get_debug()
546
Victor Stinner7b7120e2014-06-23 00:12:14 +0200547 Get the debug mode (:class:`bool`) of the event loop.
548
549 The default value is ``True`` if the environment variable
550 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
551 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100552
Victor Stinner64d750b2014-06-18 03:25:23 +0200553 .. versionadded:: 3.4.2
554
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100555.. method:: BaseEventLoop.set_debug(enabled: bool)
556
557 Set the debug mode of the event loop.
558
Victor Stinner64d750b2014-06-18 03:25:23 +0200559 .. versionadded:: 3.4.2
560
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100561.. seealso::
562
Victor Stinner62511fd2014-06-23 00:36:11 +0200563 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100564
Victor Stinner8c462c52014-01-24 18:11:43 +0100565Server
566------
567
Victor Stinner8ebeb032014-07-11 23:47:40 +0200568.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +0100569
Victor Stinner8ebeb032014-07-11 23:47:40 +0200570 Server listening on sockets.
571
572 Object created by the :meth:`BaseEventLoop.create_server` method and the
573 :func:`start_server` function. Don't instanciate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +0100574
575 .. method:: close()
576
Victor Stinner4bfb14a2014-07-12 03:20:24 +0200577 Stop serving: close listening sockets and set the :attr:`sockets`
578 attribute to ``None``.
579
580 The sockets that represent existing incoming client connections are
581 leaved open.
Victor Stinner8ebeb032014-07-11 23:47:40 +0200582
583 The server is closed asynchonously, use the :meth:`wait_closed` coroutine
584 to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100585
586 .. method:: wait_closed()
587
Victor Stinner8ebeb032014-07-11 23:47:40 +0200588 Wait until the :meth:`close` method completes.
589
590 This method is a :ref:`coroutine <coroutine>`.
591
592 .. attribute:: sockets
593
594 List of :class:`socket.socket` objects the server is listening to, or
595 ``None`` if the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100596
597
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500598Handle
599------
600
601.. class:: Handle
602
603 A callback wrapper object returned by :func:`BaseEventLoop.call_soon`,
604 :func:`BaseEventLoop.call_soon_threadsafe`, :func:`BaseEventLoop.call_later`,
605 and :func:`BaseEventLoop.call_at`.
606
607 .. method:: cancel()
608
Victor Stinneraea82292014-07-08 23:42:38 +0200609 Cancel the call.
610
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500611
612
Victor Stinner3e09e322013-12-03 01:22:06 +0100613.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100614
Victor Stinner3e09e322013-12-03 01:22:06 +0100615Example: Hello World (callback)
616-------------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100617
618Print ``Hello World`` every two seconds, using a callback::
619
620 import asyncio
621
622 def print_and_repeat(loop):
623 print('Hello World')
624 loop.call_later(2, print_and_repeat, loop)
625
626 loop = asyncio.get_event_loop()
Victor Stinnerdbd89502013-12-10 02:47:22 +0100627 loop.call_soon(print_and_repeat, loop)
Victor Stinner63b21a82014-07-05 15:38:59 +0200628 try:
629 loop.run_forever()
630 finally:
631 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100632
Victor Stinner3e09e322013-12-03 01:22:06 +0100633.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100634
Victor Stinner3e09e322013-12-03 01:22:06 +0100635 :ref:`Hello World example using a coroutine <asyncio-hello-world-coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100636
Victor Stinner8b863482014-01-27 10:07:50 +0100637
638Example: Set signal handlers for SIGINT and SIGTERM
639---------------------------------------------------
640
641Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`::
642
643 import asyncio
644 import functools
645 import os
646 import signal
647
648 def ask_exit(signame):
649 print("got signal %s: exit" % signame)
650 loop.stop()
651
652 loop = asyncio.get_event_loop()
653 for signame in ('SIGINT', 'SIGTERM'):
654 loop.add_signal_handler(getattr(signal, signame),
655 functools.partial(ask_exit, signame))
656
657 print("Event loop running forever, press CTRL+c to interrupt.")
658 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
Victor Stinner63b21a82014-07-05 15:38:59 +0200659 try:
660 loop.run_forever()
661 finally:
662 loop.close()
Victor Stinner8b863482014-01-27 10:07:50 +0100663