blob: b44fe753b80be1c47f4dde56386b193333ebe67e [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
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500340 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100341
342 .. seealso::
343
344 The :meth:`socket.socket.recv` method.
345
346.. method:: BaseEventLoop.sock_sendall(sock, data)
347
348 Send data to the socket. The socket must be connected to a remote socket.
349 This method continues to send data from *data* until either all data has
350 been sent or an error occurs. ``None`` is returned on success. On error,
351 an exception is raised, and there is no way to determine how much data, if
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500352 any, was successfully processed by the receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100353
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500354 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100355
356 .. seealso::
357
358 The :meth:`socket.socket.sendall` method.
359
360.. method:: BaseEventLoop.sock_connect(sock, address)
361
362 Connect to a remote socket at *address*.
363
Victor Stinner1b0580b2014-02-13 09:24:37 +0100364 The *address* must be already resolved to avoid the trap of hanging the
365 entire event loop when the address requires doing a DNS lookup. For
366 example, it must be an IP address, not an hostname, for
367 :py:data:`~socket.AF_INET` and :py:data:`~socket.AF_INET6` address families.
368 Use :meth:`getaddrinfo` to resolve the hostname asynchronously.
369
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500370 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100371
372 .. seealso::
373
374 The :meth:`BaseEventLoop.create_connection` method, the
375 :func:`open_connection` function and the :meth:`socket.socket.connect`
376 method.
377
378
379.. method:: BaseEventLoop.sock_accept(sock)
380
381 Accept a connection. The socket must be bound to an address and listening
382 for connections. The return value is a pair ``(conn, address)`` where *conn*
383 is a *new* socket object usable to send and receive data on the connection,
384 and *address* is the address bound to the socket on the other end of the
385 connection.
386
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500387 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100388
389 .. seealso::
390
391 The :meth:`BaseEventLoop.create_server` method, the :func:`start_server`
392 function and the :meth:`socket.socket.accept` method.
393
394
395Resolve host name
396-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100397
398.. method:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
399
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500400 This method is a :ref:`coroutine <coroutine>`, similar to
401 :meth:`socket.getaddrinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100402
403.. method:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
404
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500405 This method is a :ref:`coroutine <coroutine>`, similar to
406 :meth:`socket.getnameinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100407
408
Victor Stinner984600f2014-03-25 09:40:26 +0100409Connect pipes
410-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100411
412.. method:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
413
Victor Stinnera5b257a2014-05-29 00:14:03 +0200414 Register read pipe in eventloop. Set the *pipe* to non-blocking mode.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100415
416 *protocol_factory* should instantiate object with :class:`Protocol`
Victor Stinnera5b257a2014-05-29 00:14:03 +0200417 interface. *pipe* is a :term:`file-like object <file object>`.
418 Return pair ``(transport, protocol)``, where *transport* supports the
Victor Stinnerea3183f2013-12-03 01:08:00 +0100419 :class:`ReadTransport` interface.
420
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500421 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100422
423.. method:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
424
425 Register write pipe in eventloop.
426
427 *protocol_factory* should instantiate object with :class:`BaseProtocol`
428 interface. Pipe is file-like object already switched to nonblocking.
429 Return pair (transport, protocol), where transport support
430 :class:`WriteTransport` interface.
431
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500432 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100433
Victor Stinner08444382014-02-02 22:43:39 +0100434.. seealso::
435
Victor Stinner984600f2014-03-25 09:40:26 +0100436 The :meth:`BaseEventLoop.subprocess_exec` and
437 :meth:`BaseEventLoop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100438
Victor Stinnerea3183f2013-12-03 01:08:00 +0100439
Victor Stinner8b863482014-01-27 10:07:50 +0100440UNIX signals
441------------
442
443Availability: UNIX only.
444
445.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
446
447 Add a handler for a signal.
448
449 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
450 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
451
452.. method:: BaseEventLoop.remove_signal_handler(sig)
453
454 Remove a handler for a signal.
455
456 Return ``True`` if a signal handler was removed, ``False`` if not.
457
458.. seealso::
459
460 The :mod:`signal` module.
461
462
Victor Stinnerea3183f2013-12-03 01:08:00 +0100463Executor
464--------
465
466Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
467pool of processes). By default, an event loop uses a thread pool executor
468(:class:`~concurrent.futures.ThreadPoolExecutor`).
469
470.. method:: BaseEventLoop.run_in_executor(executor, callback, \*args)
471
472 Arrange for a callback to be called in the specified executor.
473
Larry Hastings3732ed22014-03-15 21:13:56 -0700474 The *executor* argument should be an :class:`~concurrent.futures.Executor`
475 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100476
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500477 This method is a :ref:`coroutine <coroutine>`.
478
Victor Stinnerea3183f2013-12-03 01:08:00 +0100479.. method:: BaseEventLoop.set_default_executor(executor)
480
481 Set the default executor used by :meth:`run_in_executor`.
482
483
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500484Error Handling API
485------------------
486
487Allows to customize how exceptions are handled in the event loop.
488
489.. method:: BaseEventLoop.set_exception_handler(handler)
490
491 Set *handler* as the new event loop exception handler.
492
493 If *handler* is ``None``, the default exception handler will
494 be set.
495
496 If *handler* is a callable object, it should have a
497 matching signature to ``(loop, context)``, where ``loop``
498 will be a reference to the active event loop, ``context``
499 will be a ``dict`` object (see :meth:`call_exception_handler`
500 documentation for details about context).
501
502.. method:: BaseEventLoop.default_exception_handler(context)
503
504 Default exception handler.
505
506 This is called when an exception occurs and no exception
507 handler is set, and can be called by a custom exception
508 handler that wants to defer to the default behavior.
509
510 *context* parameter has the same meaning as in
511 :meth:`call_exception_handler`.
512
513.. method:: BaseEventLoop.call_exception_handler(context)
514
515 Call the current event loop exception handler.
516
517 *context* is a ``dict`` object containing the following keys
518 (new keys may be introduced later):
519
520 * 'message': Error message;
521 * 'exception' (optional): Exception object;
522 * 'future' (optional): :class:`asyncio.Future` instance;
523 * 'handle' (optional): :class:`asyncio.Handle` instance;
524 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
525 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
526 * 'socket' (optional): :class:`socket.socket` instance.
527
528 .. note::
529
530 Note: this method should not be overloaded in subclassed
531 event loops. For any custom exception handling, use
532 :meth:`set_exception_handler()` method.
533
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100534Debug mode
535----------
536
537.. method:: BaseEventLoop.get_debug()
538
Victor Stinner7b7120e2014-06-23 00:12:14 +0200539 Get the debug mode (:class:`bool`) of the event loop.
540
541 The default value is ``True`` if the environment variable
542 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
543 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100544
Victor Stinner64d750b2014-06-18 03:25:23 +0200545 .. versionadded:: 3.4.2
546
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100547.. method:: BaseEventLoop.set_debug(enabled: bool)
548
549 Set the debug mode of the event loop.
550
Victor Stinner64d750b2014-06-18 03:25:23 +0200551 .. versionadded:: 3.4.2
552
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100553.. seealso::
554
Victor Stinner62511fd2014-06-23 00:36:11 +0200555 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100556
Victor Stinner8c462c52014-01-24 18:11:43 +0100557Server
558------
559
Victor Stinner8ebeb032014-07-11 23:47:40 +0200560.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +0100561
Victor Stinner8ebeb032014-07-11 23:47:40 +0200562 Server listening on sockets.
563
564 Object created by the :meth:`BaseEventLoop.create_server` method and the
565 :func:`start_server` function. Don't instanciate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +0100566
567 .. method:: close()
568
Victor Stinner4bfb14a2014-07-12 03:20:24 +0200569 Stop serving: close listening sockets and set the :attr:`sockets`
570 attribute to ``None``.
571
572 The sockets that represent existing incoming client connections are
573 leaved open.
Victor Stinner8ebeb032014-07-11 23:47:40 +0200574
575 The server is closed asynchonously, use the :meth:`wait_closed` coroutine
576 to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100577
578 .. method:: wait_closed()
579
Victor Stinner8ebeb032014-07-11 23:47:40 +0200580 Wait until the :meth:`close` method completes.
581
582 This method is a :ref:`coroutine <coroutine>`.
583
584 .. attribute:: sockets
585
586 List of :class:`socket.socket` objects the server is listening to, or
587 ``None`` if the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100588
589
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500590Handle
591------
592
593.. class:: Handle
594
595 A callback wrapper object returned by :func:`BaseEventLoop.call_soon`,
596 :func:`BaseEventLoop.call_soon_threadsafe`, :func:`BaseEventLoop.call_later`,
597 and :func:`BaseEventLoop.call_at`.
598
599 .. method:: cancel()
600
Victor Stinneraea82292014-07-08 23:42:38 +0200601 Cancel the call.
602
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500603
604
Victor Stinner3e09e322013-12-03 01:22:06 +0100605.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100606
Victor Stinner3e09e322013-12-03 01:22:06 +0100607Example: Hello World (callback)
608-------------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100609
610Print ``Hello World`` every two seconds, using a callback::
611
612 import asyncio
613
614 def print_and_repeat(loop):
615 print('Hello World')
616 loop.call_later(2, print_and_repeat, loop)
617
618 loop = asyncio.get_event_loop()
Victor Stinnerdbd89502013-12-10 02:47:22 +0100619 loop.call_soon(print_and_repeat, loop)
Victor Stinner63b21a82014-07-05 15:38:59 +0200620 try:
621 loop.run_forever()
622 finally:
623 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100624
Victor Stinner3e09e322013-12-03 01:22:06 +0100625.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100626
Victor Stinner3e09e322013-12-03 01:22:06 +0100627 :ref:`Hello World example using a coroutine <asyncio-hello-world-coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100628
Victor Stinner8b863482014-01-27 10:07:50 +0100629
630Example: Set signal handlers for SIGINT and SIGTERM
631---------------------------------------------------
632
633Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`::
634
635 import asyncio
636 import functools
637 import os
638 import signal
639
640 def ask_exit(signame):
641 print("got signal %s: exit" % signame)
642 loop.stop()
643
644 loop = asyncio.get_event_loop()
645 for signame in ('SIGINT', 'SIGTERM'):
646 loop.add_signal_handler(getattr(signal, signame),
647 functools.partial(ask_exit, signame))
648
649 print("Event loop running forever, press CTRL+c to interrupt.")
650 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
Victor Stinner63b21a82014-07-05 15:38:59 +0200651 try:
652 loop.run_forever()
653 finally:
654 loop.close()
Victor Stinner8b863482014-01-27 10:07:50 +0100655