blob: 6fe5aa1b2018026f33090fc34f35500747e5bd1a [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.
50 Callback scheduled after :meth:`stop` is called won't. However, those
51 callbacks will run if :meth:`run_forever` is called again later.
52
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +020053.. method:: BaseEventLoop.is_closed()
54
55 Returns ``True`` if the event loop was closed.
56
57 .. versionadded:: 3.4.2
58
Victor Stinnerea3183f2013-12-03 01:08:00 +010059.. method:: BaseEventLoop.close()
60
61 Close the event loop. The loop should not be running.
62
63 This clears the queues and shuts down the executor, but does not wait for
64 the executor to finish.
65
Victor Stinnerf328c7d2014-06-23 01:02:37 +020066 The event loop must not be running.
67
Victor Stinnerea3183f2013-12-03 01:08:00 +010068 This is idempotent and irreversible. No other methods should be called after
69 this one.
70
71
72Calls
73-----
74
75.. method:: BaseEventLoop.call_soon(callback, \*args)
76
77 Arrange for a callback to be called as soon as possible.
78
79 This operates as a FIFO queue, callbacks are called in the order in
80 which they are registered. Each callback will be called exactly once.
81
82 Any positional arguments after the callback will be passed to the
83 callback when it is called.
84
Yury Selivanov43ee1c12014-02-19 20:58:44 -050085 An instance of :class:`asyncio.Handle` is returned.
86
Victor Stinnerea3183f2013-12-03 01:08:00 +010087.. method:: BaseEventLoop.call_soon_threadsafe(callback, \*args)
88
89 Like :meth:`call_soon`, but thread safe.
90
91
Victor Stinner45b27ed2014-02-01 02:36:43 +010092.. _asyncio-delayed-calls:
93
Victor Stinnerea3183f2013-12-03 01:08:00 +010094Delayed calls
95-------------
96
97The event loop has its own internal clock for computing timeouts.
98Which clock is used depends on the (platform-specific) event loop
99implementation; ideally it is a monotonic clock. This will generally be
100a different clock than :func:`time.time`.
101
Victor Stinnerfd9d3742014-02-18 09:37:43 +0100102.. note::
103
104 Timeouts (relative *delay* or absolute *when*) should not exceed one day.
105
Victor Stinner45b27ed2014-02-01 02:36:43 +0100106
Victor Stinnerea3183f2013-12-03 01:08:00 +0100107.. method:: BaseEventLoop.call_later(delay, callback, *args)
108
109 Arrange for the *callback* to be called after the given *delay*
110 seconds (either an int or float).
111
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500112 An instance of :class:`asyncio.Handle` is returned.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100113
114 *callback* will be called exactly once per call to :meth:`call_later`.
115 If two callbacks are scheduled for exactly the same time, it is
116 undefined which will be called first.
117
118 The optional positional *args* will be passed to the callback when it
119 is called. If you want the callback to be called with some named
120 arguments, use a closure or :func:`functools.partial`.
121
122.. method:: BaseEventLoop.call_at(when, callback, *args)
123
124 Arrange for the *callback* to be called at the given absolute timestamp
125 *when* (an int or float), using the same time reference as :meth:`time`.
126
127 This method's behavior is the same as :meth:`call_later`.
128
129.. method:: BaseEventLoop.time()
130
131 Return the current time, as a :class:`float` value, according to the
132 event loop's internal clock.
133
Victor Stinner3e09e322013-12-03 01:22:06 +0100134.. seealso::
135
136 The :func:`asyncio.sleep` function.
137
Victor Stinnerea3183f2013-12-03 01:08:00 +0100138
Victor Stinner530ef2f2014-07-08 12:39:10 +0200139Coroutines
140----------
141
142.. method:: BaseEventLoop.create_task(coro)
143
144 Schedule the execution of a :ref:`coroutine object <coroutine>`: wrap it in
145 a future. Return a :class:`Task` object.
146
147 Third-party event loops can use their own subclass of :class:`Task` for
148 interoperability. In this case, the result type is a subclass of
149 :class:`Task`.
150
151 .. seealso::
152
153 The :meth:`async` function.
154
155 .. versionadded:: 3.4.2
156
157
Victor Stinnerea3183f2013-12-03 01:08:00 +0100158Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100159--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100160
161.. 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)
162
163 Create a streaming transport connection to a given Internet *host* and
Victor Stinnera6919aa2014-02-19 13:32:34 +0100164 *port*: socket family :py:data:`~socket.AF_INET` or
165 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
166 socket type :py:data:`~socket.SOCK_STREAM`. *protocol_factory* must be a
167 callable returning a :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100168
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500169 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100170 establish the connection in the background. When successful, the
171 coroutine returns a ``(transport, protocol)`` pair.
172
173 The chronological synopsis of the underlying operation is as follows:
174
Victor Stinner9592edb2014-02-02 15:03:02 +0100175 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100176 is created to represent it.
177
178 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100179 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100180
181 #. The protocol instance is tied to the transport, and its
182 :meth:`connection_made` method is called.
183
184 #. The coroutine returns successfully with the ``(transport, protocol)``
185 pair.
186
187 The created transport is an implementation-dependent bidirectional stream.
188
189 .. note::
190 *protocol_factory* can be any kind of callable, not necessarily
191 a class. For example, if you want to use a pre-created
192 protocol instance, you can pass ``lambda: my_protocol``.
193
194 Options allowing to change how the connection is created:
195
196 * *ssl*: if given and not false, a SSL/TLS transport is created
197 (by default a plain TCP transport is created). If *ssl* is
198 a :class:`ssl.SSLContext` object, this context is used to create
199 the transport; if *ssl* is :const:`True`, a context with some
200 unspecified default settings is used.
201
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100202 .. seealso:: :ref:`SSL/TLS security considerations <ssl-security>`
203
Victor Stinnerea3183f2013-12-03 01:08:00 +0100204 * *server_hostname*, is only for use together with *ssl*,
205 and sets or overrides the hostname that the target server's certificate
206 will be matched against. By default the value of the *host* argument
207 is used. If *host* is empty, there is no default and you must pass a
208 value for *server_hostname*. If *server_hostname* is an empty
209 string, hostname matching is disabled (which is a serious security
210 risk, allowing for man-in-the-middle-attacks).
211
212 * *family*, *proto*, *flags* are the optional address family, protocol
213 and flags to be passed through to getaddrinfo() for *host* resolution.
214 If given, these should all be integers from the corresponding
215 :mod:`socket` module constants.
216
217 * *sock*, if given, should be an existing, already connected
218 :class:`socket.socket` object to be used by the transport.
219 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
220 and *local_addr* should be specified.
221
222 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
223 to bind the socket to locally. The *local_host* and *local_port*
224 are looked up using getaddrinfo(), similarly to *host* and *port*.
225
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100226 .. seealso::
227
228 The :func:`open_connection` function can be used to get a pair of
229 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
230
Victor Stinnerea3183f2013-12-03 01:08:00 +0100231
Victor Stinnera6919aa2014-02-19 13:32:34 +0100232.. method:: BaseEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0)
233
234 Create datagram connection: socket family :py:data:`~socket.AF_INET` or
235 :py:data:`~socket.AF_INET6` depending on *host* (or *family* if specified),
236 socket type :py:data:`~socket.SOCK_DGRAM`.
237
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500238 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100239 establish the connection in the background. When successful, the
240 coroutine returns a ``(transport, protocol)`` pair.
241
242 See the :meth:`BaseEventLoop.create_connection` method for parameters.
243
244
245.. method:: BaseEventLoop.create_unix_connection(protocol_factory, path, \*, ssl=None, sock=None, server_hostname=None)
246
247 Create UNIX connection: socket family :py:data:`~socket.AF_UNIX`, socket
248 type :py:data:`~socket.SOCK_STREAM`. The :py:data:`~socket.AF_UNIX` socket
249 family is used to communicate between processes on the same machine
250 efficiently.
251
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500252 This method is a :ref:`coroutine <coroutine>` which will try to
Victor Stinnera6919aa2014-02-19 13:32:34 +0100253 establish the connection in the background. When successful, the
254 coroutine returns a ``(transport, protocol)`` pair.
255
256 See the :meth:`BaseEventLoop.create_connection` method for parameters.
257
258 Availability: UNIX.
259
260
Victor Stinnerea3183f2013-12-03 01:08:00 +0100261Creating listening connections
262------------------------------
263
264.. 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)
265
Victor Stinner8ebeb032014-07-11 23:47:40 +0200266 Create a TCP server bound to host and port. Return a :class:`Server` object,
267 its :attr:`~Server.sockets` attribute contains created sockets. Use the
268 :meth:`Server.close` method to stop the server: close listening sockets.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100269
Victor Stinnerd1432092014-06-19 17:11:49 +0200270 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100271
272 If *host* is an empty string or None all interfaces are assumed
273 and a list of multiple sockets will be returned (most likely
274 one for IPv4 and another one for IPv6).
275
276 *family* can be set to either :data:`~socket.AF_INET` or
277 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
278 it will be determined from host (defaults to :data:`~socket.AF_UNSPEC`).
279
280 *flags* is a bitmask for :meth:`getaddrinfo`.
281
282 *sock* can optionally be specified in order to use a preexisting
283 socket object.
284
285 *backlog* is the maximum number of queued connections passed to
286 :meth:`~socket.socket.listen` (defaults to 100).
287
288 ssl can be set to an :class:`~ssl.SSLContext` to enable SSL over the
289 accepted connections.
290
291 *reuse_address* tells the kernel to reuse a local socket in
292 TIME_WAIT state, without waiting for its natural timeout to
293 expire. If not specified will automatically be set to True on
294 UNIX.
295
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100296 .. seealso::
297
298 The function :func:`start_server` creates a (:class:`StreamReader`,
299 :class:`StreamWriter`) pair and calls back a function with this pair.
300
Victor Stinnerea3183f2013-12-03 01:08:00 +0100301
Victor Stinnera6919aa2014-02-19 13:32:34 +0100302.. method:: BaseEventLoop.create_unix_server(protocol_factory, path=None, \*, sock=None, backlog=100, ssl=None)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100303
Victor Stinnera6919aa2014-02-19 13:32:34 +0100304 Similar to :meth:`BaseEventLoop.create_server`, but specific to the
305 socket family :py:data:`~socket.AF_UNIX`.
306
307 Availability: UNIX.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100308
309
Victor Stinnerc1567df2014-02-08 23:22:58 +0100310Watch file descriptors
311----------------------
312
313.. method:: BaseEventLoop.add_reader(fd, callback, \*args)
314
315 Start watching the file descriptor for read availability and then call the
316 *callback* with specified arguments.
317
318.. method:: BaseEventLoop.remove_reader(fd)
319
320 Stop watching the file descriptor for read availability.
321
322.. method:: BaseEventLoop.add_writer(fd, callback, \*args)
323
324 Start watching the file descriptor for write availability and then call the
325 *callback* with specified arguments.
326
327.. method:: BaseEventLoop.remove_writer(fd)
328
329 Stop watching the file descriptor for write availability.
330
331
332Low-level socket operations
333---------------------------
334
335.. method:: BaseEventLoop.sock_recv(sock, nbytes)
336
337 Receive data from the socket. The return value is a bytes object
338 representing the data received. The maximum amount of data to be received
339 at once is specified by *nbytes*.
340
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500341 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100342
343 .. seealso::
344
345 The :meth:`socket.socket.recv` method.
346
347.. method:: BaseEventLoop.sock_sendall(sock, data)
348
349 Send data to the socket. The socket must be connected to a remote socket.
350 This method continues to send data from *data* until either all data has
351 been sent or an error occurs. ``None`` is returned on success. On error,
352 an exception is raised, and there is no way to determine how much data, if
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500353 any, was successfully processed by the receiving end of the connection.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100354
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500355 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100356
357 .. seealso::
358
359 The :meth:`socket.socket.sendall` method.
360
361.. method:: BaseEventLoop.sock_connect(sock, address)
362
363 Connect to a remote socket at *address*.
364
Victor Stinner1b0580b2014-02-13 09:24:37 +0100365 The *address* must be already resolved to avoid the trap of hanging the
366 entire event loop when the address requires doing a DNS lookup. For
367 example, it must be an IP address, not an hostname, for
368 :py:data:`~socket.AF_INET` and :py:data:`~socket.AF_INET6` address families.
369 Use :meth:`getaddrinfo` to resolve the hostname asynchronously.
370
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500371 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100372
373 .. seealso::
374
375 The :meth:`BaseEventLoop.create_connection` method, the
376 :func:`open_connection` function and the :meth:`socket.socket.connect`
377 method.
378
379
380.. method:: BaseEventLoop.sock_accept(sock)
381
382 Accept a connection. The socket must be bound to an address and listening
383 for connections. The return value is a pair ``(conn, address)`` where *conn*
384 is a *new* socket object usable to send and receive data on the connection,
385 and *address* is the address bound to the socket on the other end of the
386 connection.
387
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500388 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerc1567df2014-02-08 23:22:58 +0100389
390 .. seealso::
391
392 The :meth:`BaseEventLoop.create_server` method, the :func:`start_server`
393 function and the :meth:`socket.socket.accept` method.
394
395
396Resolve host name
397-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100398
399.. method:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
400
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500401 This method is a :ref:`coroutine <coroutine>`, similar to
402 :meth:`socket.getaddrinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100403
404.. method:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
405
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500406 This method is a :ref:`coroutine <coroutine>`, similar to
407 :meth:`socket.getnameinfo` function but non-blocking.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100408
409
Victor Stinner984600f2014-03-25 09:40:26 +0100410Connect pipes
411-------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100412
413.. method:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
414
Victor Stinnera5b257a2014-05-29 00:14:03 +0200415 Register read pipe in eventloop. Set the *pipe* to non-blocking mode.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100416
417 *protocol_factory* should instantiate object with :class:`Protocol`
Victor Stinnera5b257a2014-05-29 00:14:03 +0200418 interface. *pipe* is a :term:`file-like object <file object>`.
419 Return pair ``(transport, protocol)``, where *transport* supports the
Victor Stinnerea3183f2013-12-03 01:08:00 +0100420 :class:`ReadTransport` interface.
421
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500422 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100423
424.. method:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
425
426 Register write pipe in eventloop.
427
428 *protocol_factory* should instantiate object with :class:`BaseProtocol`
429 interface. Pipe is file-like object already switched to nonblocking.
430 Return pair (transport, protocol), where transport support
431 :class:`WriteTransport` interface.
432
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500433 This method is a :ref:`coroutine <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100434
Victor Stinner08444382014-02-02 22:43:39 +0100435.. seealso::
436
Victor Stinner984600f2014-03-25 09:40:26 +0100437 The :meth:`BaseEventLoop.subprocess_exec` and
438 :meth:`BaseEventLoop.subprocess_shell` methods.
Victor Stinner08444382014-02-02 22:43:39 +0100439
Victor Stinnerea3183f2013-12-03 01:08:00 +0100440
Victor Stinner8b863482014-01-27 10:07:50 +0100441UNIX signals
442------------
443
444Availability: UNIX only.
445
446.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
447
448 Add a handler for a signal.
449
450 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
451 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
452
453.. method:: BaseEventLoop.remove_signal_handler(sig)
454
455 Remove a handler for a signal.
456
457 Return ``True`` if a signal handler was removed, ``False`` if not.
458
459.. seealso::
460
461 The :mod:`signal` module.
462
463
Victor Stinnerea3183f2013-12-03 01:08:00 +0100464Executor
465--------
466
467Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
468pool of processes). By default, an event loop uses a thread pool executor
469(:class:`~concurrent.futures.ThreadPoolExecutor`).
470
471.. method:: BaseEventLoop.run_in_executor(executor, callback, \*args)
472
473 Arrange for a callback to be called in the specified executor.
474
Larry Hastings3732ed22014-03-15 21:13:56 -0700475 The *executor* argument should be an :class:`~concurrent.futures.Executor`
476 instance. The default executor is used if *executor* is ``None``.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100477
Yury Selivanov37f15bc2014-02-20 16:20:44 -0500478 This method is a :ref:`coroutine <coroutine>`.
479
Victor Stinnerea3183f2013-12-03 01:08:00 +0100480.. method:: BaseEventLoop.set_default_executor(executor)
481
482 Set the default executor used by :meth:`run_in_executor`.
483
484
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500485Error Handling API
486------------------
487
488Allows to customize how exceptions are handled in the event loop.
489
490.. method:: BaseEventLoop.set_exception_handler(handler)
491
492 Set *handler* as the new event loop exception handler.
493
494 If *handler* is ``None``, the default exception handler will
495 be set.
496
497 If *handler* is a callable object, it should have a
498 matching signature to ``(loop, context)``, where ``loop``
499 will be a reference to the active event loop, ``context``
500 will be a ``dict`` object (see :meth:`call_exception_handler`
501 documentation for details about context).
502
503.. method:: BaseEventLoop.default_exception_handler(context)
504
505 Default exception handler.
506
507 This is called when an exception occurs and no exception
508 handler is set, and can be called by a custom exception
509 handler that wants to defer to the default behavior.
510
511 *context* parameter has the same meaning as in
512 :meth:`call_exception_handler`.
513
514.. method:: BaseEventLoop.call_exception_handler(context)
515
516 Call the current event loop exception handler.
517
518 *context* is a ``dict`` object containing the following keys
519 (new keys may be introduced later):
520
521 * 'message': Error message;
522 * 'exception' (optional): Exception object;
523 * 'future' (optional): :class:`asyncio.Future` instance;
524 * 'handle' (optional): :class:`asyncio.Handle` instance;
525 * 'protocol' (optional): :ref:`Protocol <asyncio-protocol>` instance;
526 * 'transport' (optional): :ref:`Transport <asyncio-transport>` instance;
527 * 'socket' (optional): :class:`socket.socket` instance.
528
529 .. note::
530
531 Note: this method should not be overloaded in subclassed
532 event loops. For any custom exception handling, use
533 :meth:`set_exception_handler()` method.
534
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100535Debug mode
536----------
537
538.. method:: BaseEventLoop.get_debug()
539
Victor Stinner7b7120e2014-06-23 00:12:14 +0200540 Get the debug mode (:class:`bool`) of the event loop.
541
542 The default value is ``True`` if the environment variable
543 :envvar:`PYTHONASYNCIODEBUG` is set to a non-empty string, ``False``
544 otherwise.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100545
Victor Stinner64d750b2014-06-18 03:25:23 +0200546 .. versionadded:: 3.4.2
547
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100548.. method:: BaseEventLoop.set_debug(enabled: bool)
549
550 Set the debug mode of the event loop.
551
Victor Stinner64d750b2014-06-18 03:25:23 +0200552 .. versionadded:: 3.4.2
553
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100554.. seealso::
555
Victor Stinner62511fd2014-06-23 00:36:11 +0200556 The :ref:`debug mode of asyncio <asyncio-debug-mode>`.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100557
Victor Stinner8c462c52014-01-24 18:11:43 +0100558Server
559------
560
Victor Stinner8ebeb032014-07-11 23:47:40 +0200561.. class:: Server
Victor Stinner8c462c52014-01-24 18:11:43 +0100562
Victor Stinner8ebeb032014-07-11 23:47:40 +0200563 Server listening on sockets.
564
565 Object created by the :meth:`BaseEventLoop.create_server` method and the
566 :func:`start_server` function. Don't instanciate the class directly.
Victor Stinner8c462c52014-01-24 18:11:43 +0100567
568 .. method:: close()
569
Victor Stinner4bfb14a2014-07-12 03:20:24 +0200570 Stop serving: close listening sockets and set the :attr:`sockets`
571 attribute to ``None``.
572
573 The sockets that represent existing incoming client connections are
574 leaved open.
Victor Stinner8ebeb032014-07-11 23:47:40 +0200575
576 The server is closed asynchonously, use the :meth:`wait_closed` coroutine
577 to wait until the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100578
579 .. method:: wait_closed()
580
Victor Stinner8ebeb032014-07-11 23:47:40 +0200581 Wait until the :meth:`close` method completes.
582
583 This method is a :ref:`coroutine <coroutine>`.
584
585 .. attribute:: sockets
586
587 List of :class:`socket.socket` objects the server is listening to, or
588 ``None`` if the server is closed.
Victor Stinner8c462c52014-01-24 18:11:43 +0100589
590
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500591Handle
592------
593
594.. class:: Handle
595
596 A callback wrapper object returned by :func:`BaseEventLoop.call_soon`,
597 :func:`BaseEventLoop.call_soon_threadsafe`, :func:`BaseEventLoop.call_later`,
598 and :func:`BaseEventLoop.call_at`.
599
600 .. method:: cancel()
601
Victor Stinneraea82292014-07-08 23:42:38 +0200602 Cancel the call.
603
Yury Selivanov43ee1c12014-02-19 20:58:44 -0500604
605
Victor Stinner3e09e322013-12-03 01:22:06 +0100606.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100607
Victor Stinner3e09e322013-12-03 01:22:06 +0100608Example: Hello World (callback)
609-------------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100610
611Print ``Hello World`` every two seconds, using a callback::
612
613 import asyncio
614
615 def print_and_repeat(loop):
616 print('Hello World')
617 loop.call_later(2, print_and_repeat, loop)
618
619 loop = asyncio.get_event_loop()
Victor Stinnerdbd89502013-12-10 02:47:22 +0100620 loop.call_soon(print_and_repeat, loop)
Victor Stinner63b21a82014-07-05 15:38:59 +0200621 try:
622 loop.run_forever()
623 finally:
624 loop.close()
Victor Stinnerea3183f2013-12-03 01:08:00 +0100625
Victor Stinner3e09e322013-12-03 01:22:06 +0100626.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100627
Victor Stinner3e09e322013-12-03 01:22:06 +0100628 :ref:`Hello World example using a coroutine <asyncio-hello-world-coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100629
Victor Stinner8b863482014-01-27 10:07:50 +0100630
631Example: Set signal handlers for SIGINT and SIGTERM
632---------------------------------------------------
633
634Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`::
635
636 import asyncio
637 import functools
638 import os
639 import signal
640
641 def ask_exit(signame):
642 print("got signal %s: exit" % signame)
643 loop.stop()
644
645 loop = asyncio.get_event_loop()
646 for signame in ('SIGINT', 'SIGTERM'):
647 loop.add_signal_handler(getattr(signal, signame),
648 functools.partial(ask_exit, signame))
649
650 print("Event loop running forever, press CTRL+c to interrupt.")
651 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
Victor Stinner63b21a82014-07-05 15:38:59 +0200652 try:
653 loop.run_forever()
654 finally:
655 loop.close()
Victor Stinner8b863482014-01-27 10:07:50 +0100656