blob: fcaf5e52a855340b82464ba5411915c852f5d319 [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
11* Registering, executing and cancelling delayed calls (timeouts)
12
Victor Stinner9592edb2014-02-02 15:03:02 +010013* Creating client and server :ref:`transports <asyncio-transport>` for various
Victor Stinnerea3183f2013-12-03 01:08:00 +010014 kinds of communication
15
Victor Stinner9592edb2014-02-02 15:03:02 +010016* Launching subprocesses and the associated :ref:`transports <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +010017 for communication with an external program
18
19* Delegating costly function calls to a pool of threads
20
21Event loop functions
22--------------------
23
24The easiest way to get an event loop is to call the :func:`get_event_loop`
25function.
26
27.. function:: get_event_loop()
28
29 Get the event loop for current context. Returns an event loop object
30 implementing :class:`BaseEventLoop` interface, or raises an exception in case no
31 event loop has been set for the current context and the current policy does
32 not specify to create one. It should never return ``None``.
33
34.. function:: set_event_loop(loop)
35
36 XXX
37
38.. function:: new_event_loop()
39
40 XXX
41
42
43Event loop policy
44-----------------
45
46.. function:: get_event_loop_policy()
47
48 XXX
49
50.. function:: set_event_loop_policy(policy)
51
52 XXX
53
54
55Run an event loop
56-----------------
57
58.. method:: BaseEventLoop.run_forever()
59
60 Run until :meth:`stop` is called.
61
62.. method:: BaseEventLoop.run_until_complete(future)
63
Victor Stinner99c2ab42013-12-03 19:17:25 +010064 Run until the :class:`Future` is done.
Victor Stinnerea3183f2013-12-03 01:08:00 +010065
66 If the argument is a coroutine, it is wrapped in a :class:`Task`.
67
68 Return the Future's result, or raise its exception.
69
70.. method:: BaseEventLoop.is_running()
71
72 Returns running status of event loop.
73
Victor Stinnerafbf8272013-12-03 02:05:42 +010074.. method:: BaseEventLoop.stop()
Victor Stinnerea3183f2013-12-03 01:08:00 +010075
76 Stop running the event loop.
77
78 Every callback scheduled before :meth:`stop` is called will run.
79 Callback scheduled after :meth:`stop` is called won't. However, those
80 callbacks will run if :meth:`run_forever` is called again later.
81
82.. method:: BaseEventLoop.close()
83
84 Close the event loop. The loop should not be running.
85
86 This clears the queues and shuts down the executor, but does not wait for
87 the executor to finish.
88
89 This is idempotent and irreversible. No other methods should be called after
90 this one.
91
92
93Calls
94-----
95
96.. method:: BaseEventLoop.call_soon(callback, \*args)
97
98 Arrange for a callback to be called as soon as possible.
99
100 This operates as a FIFO queue, callbacks are called in the order in
101 which they are registered. Each callback will be called exactly once.
102
103 Any positional arguments after the callback will be passed to the
104 callback when it is called.
105
106.. method:: BaseEventLoop.call_soon_threadsafe(callback, \*args)
107
108 Like :meth:`call_soon`, but thread safe.
109
110
Victor Stinner45b27ed2014-02-01 02:36:43 +0100111.. _asyncio-delayed-calls:
112
Victor Stinnerea3183f2013-12-03 01:08:00 +0100113Delayed calls
114-------------
115
116The event loop has its own internal clock for computing timeouts.
117Which clock is used depends on the (platform-specific) event loop
118implementation; ideally it is a monotonic clock. This will generally be
119a different clock than :func:`time.time`.
120
Victor Stinner45b27ed2014-02-01 02:36:43 +0100121
Victor Stinnerea3183f2013-12-03 01:08:00 +0100122.. method:: BaseEventLoop.call_later(delay, callback, *args)
123
124 Arrange for the *callback* to be called after the given *delay*
125 seconds (either an int or float).
126
127 A "handle" is returned: an opaque object with a :meth:`cancel` method
128 that can be used to cancel the call.
129
130 *callback* will be called exactly once per call to :meth:`call_later`.
131 If two callbacks are scheduled for exactly the same time, it is
132 undefined which will be called first.
133
134 The optional positional *args* will be passed to the callback when it
135 is called. If you want the callback to be called with some named
136 arguments, use a closure or :func:`functools.partial`.
137
138.. method:: BaseEventLoop.call_at(when, callback, *args)
139
140 Arrange for the *callback* to be called at the given absolute timestamp
141 *when* (an int or float), using the same time reference as :meth:`time`.
142
143 This method's behavior is the same as :meth:`call_later`.
144
145.. method:: BaseEventLoop.time()
146
147 Return the current time, as a :class:`float` value, according to the
148 event loop's internal clock.
149
Victor Stinner3e09e322013-12-03 01:22:06 +0100150.. seealso::
151
152 The :func:`asyncio.sleep` function.
153
Victor Stinnerea3183f2013-12-03 01:08:00 +0100154
155Creating connections
Victor Stinner0c6f1ca2013-12-03 01:46:39 +0100156--------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100157
158.. 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)
159
160 Create a streaming transport connection to a given Internet *host* and
161 *port*. *protocol_factory* must be a callable returning a
Victor Stinner9592edb2014-02-02 15:03:02 +0100162 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100163
Victor Stinner59759ff2014-01-16 19:30:21 +0100164 This method returns a :ref:`coroutine object <coroutine>` which will try to
Victor Stinnerea3183f2013-12-03 01:08:00 +0100165 establish the connection in the background. When successful, the
166 coroutine returns a ``(transport, protocol)`` pair.
167
168 The chronological synopsis of the underlying operation is as follows:
169
Victor Stinner9592edb2014-02-02 15:03:02 +0100170 #. The connection is established, and a :ref:`transport <asyncio-transport>`
Victor Stinnerea3183f2013-12-03 01:08:00 +0100171 is created to represent it.
172
173 #. *protocol_factory* is called without arguments and must return a
Victor Stinner9592edb2014-02-02 15:03:02 +0100174 :ref:`protocol <asyncio-protocol>` instance.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100175
176 #. The protocol instance is tied to the transport, and its
177 :meth:`connection_made` method is called.
178
179 #. The coroutine returns successfully with the ``(transport, protocol)``
180 pair.
181
182 The created transport is an implementation-dependent bidirectional stream.
183
184 .. note::
185 *protocol_factory* can be any kind of callable, not necessarily
186 a class. For example, if you want to use a pre-created
187 protocol instance, you can pass ``lambda: my_protocol``.
188
189 Options allowing to change how the connection is created:
190
191 * *ssl*: if given and not false, a SSL/TLS transport is created
192 (by default a plain TCP transport is created). If *ssl* is
193 a :class:`ssl.SSLContext` object, this context is used to create
194 the transport; if *ssl* is :const:`True`, a context with some
195 unspecified default settings is used.
196
197 * *server_hostname*, is only for use together with *ssl*,
198 and sets or overrides the hostname that the target server's certificate
199 will be matched against. By default the value of the *host* argument
200 is used. If *host* is empty, there is no default and you must pass a
201 value for *server_hostname*. If *server_hostname* is an empty
202 string, hostname matching is disabled (which is a serious security
203 risk, allowing for man-in-the-middle-attacks).
204
205 * *family*, *proto*, *flags* are the optional address family, protocol
206 and flags to be passed through to getaddrinfo() for *host* resolution.
207 If given, these should all be integers from the corresponding
208 :mod:`socket` module constants.
209
210 * *sock*, if given, should be an existing, already connected
211 :class:`socket.socket` object to be used by the transport.
212 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
213 and *local_addr* should be specified.
214
215 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
216 to bind the socket to locally. The *local_host* and *local_port*
217 are looked up using getaddrinfo(), similarly to *host* and *port*.
218
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100219 .. seealso::
220
221 The :func:`open_connection` function can be used to get a pair of
222 (:class:`StreamReader`, :class:`StreamWriter`) instead of a protocol.
223
Victor Stinnerea3183f2013-12-03 01:08:00 +0100224
225Creating listening connections
226------------------------------
227
228.. 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)
229
Victor Stinner59759ff2014-01-16 19:30:21 +0100230 A :ref:`coroutine function <coroutine>` which creates a TCP server bound to host and
Victor Stinnerea3183f2013-12-03 01:08:00 +0100231 port.
232
233 The return value is a :class:`AbstractServer` object which can be used to stop
234 the service.
235
236 If *host* is an empty string or None all interfaces are assumed
237 and a list of multiple sockets will be returned (most likely
238 one for IPv4 and another one for IPv6).
239
240 *family* can be set to either :data:`~socket.AF_INET` or
241 :data:`~socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set
242 it will be determined from host (defaults to :data:`~socket.AF_UNSPEC`).
243
244 *flags* is a bitmask for :meth:`getaddrinfo`.
245
246 *sock* can optionally be specified in order to use a preexisting
247 socket object.
248
249 *backlog* is the maximum number of queued connections passed to
250 :meth:`~socket.socket.listen` (defaults to 100).
251
252 ssl can be set to an :class:`~ssl.SSLContext` to enable SSL over the
253 accepted connections.
254
255 *reuse_address* tells the kernel to reuse a local socket in
256 TIME_WAIT state, without waiting for its natural timeout to
257 expire. If not specified will automatically be set to True on
258 UNIX.
259
Victor Stinner59759ff2014-01-16 19:30:21 +0100260 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100261
Victor Stinnerc8ea8132014-01-23 11:02:09 +0100262 .. seealso::
263
264 The function :func:`start_server` creates a (:class:`StreamReader`,
265 :class:`StreamWriter`) pair and calls back a function with this pair.
266
Victor Stinnerea3183f2013-12-03 01:08:00 +0100267.. method:: BaseEventLoop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, \*, family=0, proto=0, flags=0)
268
269 Create datagram connection.
270
Victor Stinner59759ff2014-01-16 19:30:21 +0100271 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100272
273
274
Victor Stinnerc1567df2014-02-08 23:22:58 +0100275Watch file descriptors
276----------------------
277
278.. method:: BaseEventLoop.add_reader(fd, callback, \*args)
279
280 Start watching the file descriptor for read availability and then call the
281 *callback* with specified arguments.
282
283.. method:: BaseEventLoop.remove_reader(fd)
284
285 Stop watching the file descriptor for read availability.
286
287.. method:: BaseEventLoop.add_writer(fd, callback, \*args)
288
289 Start watching the file descriptor for write availability and then call the
290 *callback* with specified arguments.
291
292.. method:: BaseEventLoop.remove_writer(fd)
293
294 Stop watching the file descriptor for write availability.
295
296
297Low-level socket operations
298---------------------------
299
300.. method:: BaseEventLoop.sock_recv(sock, nbytes)
301
302 Receive data from the socket. The return value is a bytes object
303 representing the data received. The maximum amount of data to be received
304 at once is specified by *nbytes*.
305
306 This method returns a :ref:`coroutine object <coroutine>`.
307
308 .. seealso::
309
310 The :meth:`socket.socket.recv` method.
311
312.. method:: BaseEventLoop.sock_sendall(sock, data)
313
314 Send data to the socket. The socket must be connected to a remote socket.
315 This method continues to send data from *data* until either all data has
316 been sent or an error occurs. ``None`` is returned on success. On error,
317 an exception is raised, and there is no way to determine how much data, if
318 any, was successfully sent.
319
320 This method returns a :ref:`coroutine object <coroutine>`.
321
322 .. seealso::
323
324 The :meth:`socket.socket.sendall` method.
325
326.. method:: BaseEventLoop.sock_connect(sock, address)
327
328 Connect to a remote socket at *address*.
329
330 This method returns a :ref:`coroutine object <coroutine>`.
331
332 .. seealso::
333
334 The :meth:`BaseEventLoop.create_connection` method, the
335 :func:`open_connection` function and the :meth:`socket.socket.connect`
336 method.
337
338
339.. method:: BaseEventLoop.sock_accept(sock)
340
341 Accept a connection. The socket must be bound to an address and listening
342 for connections. The return value is a pair ``(conn, address)`` where *conn*
343 is a *new* socket object usable to send and receive data on the connection,
344 and *address* is the address bound to the socket on the other end of the
345 connection.
346
347 This method returns a :ref:`coroutine object <coroutine>`.
348
349 .. seealso::
350
351 The :meth:`BaseEventLoop.create_server` method, the :func:`start_server`
352 function and the :meth:`socket.socket.accept` method.
353
354
355Resolve host name
356-----------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100357
358.. method:: BaseEventLoop.getaddrinfo(host, port, \*, family=0, type=0, proto=0, flags=0)
359
Victor Stinnerc1567df2014-02-08 23:22:58 +0100360 Similar to the :meth:`socket.getaddrinfo` function, but return a
361 :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100362
363.. method:: BaseEventLoop.getnameinfo(sockaddr, flags=0)
364
Victor Stinnerc1567df2014-02-08 23:22:58 +0100365 Similar to the :meth:`socket.getnameinfo` function, but return a
366 :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100367
368
369Running subprocesses
370--------------------
371
372Run subprocesses asynchronously using the :mod:`subprocess` module.
373
Victor Stinner041ff9b2014-01-28 02:24:22 +0100374.. note::
375
376 On Windows, the default event loop uses
377 :class:`selectors.SelectSelector` which only supports sockets. The
Victor Stinner45b27ed2014-02-01 02:36:43 +0100378 :class:`ProactorEventLoop` should be used to support subprocesses.
Victor Stinner041ff9b2014-01-28 02:24:22 +0100379
380.. note::
381
Ned Deilyeecbbad2014-01-27 19:03:07 -0700382 On Mac OS X older than 10.9 (Mavericks), :class:`selectors.KqueueSelector`
Victor Stinner041ff9b2014-01-28 02:24:22 +0100383 does not support character devices like PTY, whereas it is used by the
384 default event loop. The :class:`SelectorEventLoop` can be used with
Victor Stinner3bc647c2014-02-03 00:35:46 +0100385 :class:`SelectSelector` or :class:`PollSelector` to handle character devices
386 on Mac OS X 10.6 (Snow Leopard) and later.
Victor Stinner041ff9b2014-01-28 02:24:22 +0100387
Victor Stinnerea3183f2013-12-03 01:08:00 +0100388.. method:: BaseEventLoop.subprocess_exec(protocol_factory, \*args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=False, shell=False, bufsize=0, \*\*kwargs)
389
390 XXX
391
Victor Stinner59759ff2014-01-16 19:30:21 +0100392 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100393
394 See the constructor of the :class:`subprocess.Popen` class for parameters.
395
396.. method:: BaseEventLoop.subprocess_shell(protocol_factory, cmd, \*, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=False, shell=True, bufsize=0, \*\*kwargs)
397
398 XXX
399
Victor Stinner59759ff2014-01-16 19:30:21 +0100400 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100401
402 See the constructor of the :class:`subprocess.Popen` class for parameters.
403
404.. method:: BaseEventLoop.connect_read_pipe(protocol_factory, pipe)
405
406 Register read pipe in eventloop.
407
408 *protocol_factory* should instantiate object with :class:`Protocol`
409 interface. pipe is file-like object already switched to nonblocking.
410 Return pair (transport, protocol), where transport support
411 :class:`ReadTransport` interface.
412
Victor Stinner59759ff2014-01-16 19:30:21 +0100413 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100414
415.. method:: BaseEventLoop.connect_write_pipe(protocol_factory, pipe)
416
417 Register write pipe in eventloop.
418
419 *protocol_factory* should instantiate object with :class:`BaseProtocol`
420 interface. Pipe is file-like object already switched to nonblocking.
421 Return pair (transport, protocol), where transport support
422 :class:`WriteTransport` interface.
423
Victor Stinner59759ff2014-01-16 19:30:21 +0100424 This method returns a :ref:`coroutine object <coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100425
Victor Stinner08444382014-02-02 22:43:39 +0100426.. seealso::
427
428 The :func:`create_subprocess_exec` and :func:`create_subprocess_shell`
429 functions.
430
Victor Stinnerea3183f2013-12-03 01:08:00 +0100431
Victor Stinner8b863482014-01-27 10:07:50 +0100432UNIX signals
433------------
434
435Availability: UNIX only.
436
437.. method:: BaseEventLoop.add_signal_handler(signum, callback, \*args)
438
439 Add a handler for a signal.
440
441 Raise :exc:`ValueError` if the signal number is invalid or uncatchable.
442 Raise :exc:`RuntimeError` if there is a problem setting up the handler.
443
444.. method:: BaseEventLoop.remove_signal_handler(sig)
445
446 Remove a handler for a signal.
447
448 Return ``True`` if a signal handler was removed, ``False`` if not.
449
450.. seealso::
451
452 The :mod:`signal` module.
453
454
Victor Stinnerea3183f2013-12-03 01:08:00 +0100455Executor
456--------
457
458Call a function in an :class:`~concurrent.futures.Executor` (pool of threads or
459pool of processes). By default, an event loop uses a thread pool executor
460(:class:`~concurrent.futures.ThreadPoolExecutor`).
461
462.. method:: BaseEventLoop.run_in_executor(executor, callback, \*args)
463
464 Arrange for a callback to be called in the specified executor.
465
466 *executor* is a :class:`~concurrent.futures.Executor` instance,
467 the default executor is used if *executor* is ``None``.
468
469.. method:: BaseEventLoop.set_default_executor(executor)
470
471 Set the default executor used by :meth:`run_in_executor`.
472
473
Victor Stinner8c462c52014-01-24 18:11:43 +0100474Server
475------
476
477.. class:: AbstractServer
478
479 Abstract server returned by :func:`BaseEventLoop.create_server`.
480
481 .. method:: close()
482
483 Stop serving. This leaves existing connections open.
484
485 .. method:: wait_closed()
486
487 Coroutine to wait until service is closed.
488
489
Victor Stinner3e09e322013-12-03 01:22:06 +0100490.. _asyncio-hello-world-callback:
Victor Stinnerea3183f2013-12-03 01:08:00 +0100491
Victor Stinner3e09e322013-12-03 01:22:06 +0100492Example: Hello World (callback)
493-------------------------------
Victor Stinnerea3183f2013-12-03 01:08:00 +0100494
495Print ``Hello World`` every two seconds, using a callback::
496
497 import asyncio
498
499 def print_and_repeat(loop):
500 print('Hello World')
501 loop.call_later(2, print_and_repeat, loop)
502
503 loop = asyncio.get_event_loop()
Victor Stinnerdbd89502013-12-10 02:47:22 +0100504 loop.call_soon(print_and_repeat, loop)
Victor Stinnerea3183f2013-12-03 01:08:00 +0100505 loop.run_forever()
506
Victor Stinner3e09e322013-12-03 01:22:06 +0100507.. seealso::
Victor Stinnerea3183f2013-12-03 01:08:00 +0100508
Victor Stinner3e09e322013-12-03 01:22:06 +0100509 :ref:`Hello World example using a coroutine <asyncio-hello-world-coroutine>`.
Victor Stinnerea3183f2013-12-03 01:08:00 +0100510
Victor Stinner8b863482014-01-27 10:07:50 +0100511
512Example: Set signal handlers for SIGINT and SIGTERM
513---------------------------------------------------
514
515Register handlers for signals :py:data:`SIGINT` and :py:data:`SIGTERM`::
516
517 import asyncio
518 import functools
519 import os
520 import signal
521
522 def ask_exit(signame):
523 print("got signal %s: exit" % signame)
524 loop.stop()
525
526 loop = asyncio.get_event_loop()
527 for signame in ('SIGINT', 'SIGTERM'):
528 loop.add_signal_handler(getattr(signal, signame),
529 functools.partial(ask_exit, signame))
530
531 print("Event loop running forever, press CTRL+c to interrupt.")
532 print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())
533 loop.run_forever()
534