blob: 7b8151fc0d9b144fd0c42c94bb7ec832eb18c2ca [file] [log] [blame]
Guido van Rossum7a465642013-11-22 11:47:22 -08001:mod:`asyncio` -- Asynchronous I/O, event loop, coroutines and tasks
2====================================================================
3
4.. module:: asyncio
5 :synopsis: Asynchronous I/O, event loop, coroutines and tasks.
6
7.. versionadded:: 3.4
8
Guido van Rossumf8d0ff92013-11-22 16:53:25 -08009**Source code:** :source:`Lib/asyncio/`
10
11--------------
Guido van Rossum7a465642013-11-22 11:47:22 -080012
Antoine Pitroubba86822013-11-23 00:34:26 +010013This module provides infrastructure for writing single-threaded concurrent
14code using coroutines, multiplexing I/O access over sockets and other
15resources, running network clients and servers, and other related primitives.
Guido van Rossum7a465642013-11-22 11:47:22 -080016
Antoine Pitroubba86822013-11-23 00:34:26 +010017Here is a more detailed list of the package contents:
18
19* a pluggable :ref:`event loop <event-loop>` with various system-specific
20 implementations;
21
22* :ref:`transport <transport>` and :ref:`protocol <protocol>` abstractions
23 (similar to those in `Twisted <http://twistedmatrix.com/>`_);
24
25* concrete support for TCP, UDP, SSL, subprocess pipes, delayed calls, and
26 others (some may be system-dependent);
27
28* a Future class that mimicks the one in the :mod:`concurrent.futures` module,
29 but adapted for use with the event loop;
30
31* coroutines and tasks based on ``yield from`` (:PEP:`380`), to help write
32 concurrent code in a sequential fashion;
33
34* cancellation support for Futures and coroutines;
35
36* :ref:`synchronization primitives <sync>` for use between coroutines in
37 a single thread, mimicking those in the :mod:`threading` module;
38
Guido van Rossumf0f5d382013-11-22 15:45:02 -080039* an interface for passing work off to a threadpool, for times when
40 you absolutely, positively have to use a library that makes blocking
41 I/O calls.
42
Antoine Pitroubba86822013-11-23 00:34:26 +010043
44Disclaimer
45----------
Guido van Rossum7a465642013-11-22 11:47:22 -080046
47Full documentation is not yet ready; we hope to have it written
48before Python 3.4 leaves beta. Until then, the best reference is
49:PEP:`3156`. For a motivational primer on transports and protocols,
50see :PEP:`3153`.
Antoine Pitroubba86822013-11-23 00:34:26 +010051
52
53.. XXX should the asyncio documentation come in several pages, as for logging?
54
55
56.. _event-loop:
57
58Event loops
59-----------
60
Antoine Pitrou9a62a192013-11-23 13:10:08 +010061The event loop is the central execution device provided by :mod:`asyncio`.
62It provides multiple facilities, amongst which:
63
64* Registering, executing and cancelling delayed calls (timeouts)
65
66* Creating client and server :ref:`transports <transport>` for various
67 kinds of communication
68
69* Launching subprocesses and the associated :ref:`transports <transport>`
70 for communication with an external program
71
72* Delegating costly function calls to a pool of threads
73
74Getting an event loop
75^^^^^^^^^^^^^^^^^^^^^
76
77The easiest way to get an event loop is to call the :func:`get_event_loop`
78function.
79
80.. XXX more docs
81
82Delayed calls
83^^^^^^^^^^^^^
84
85The event loop has its own internal clock for computing timeouts.
86Which clock is used depends on the (platform-specific) event loop
87implementation; ideally it is a monotonic clock. This will generally be
88a different clock than :func:`time.time`.
89
90.. method:: time()
91
92 Return the current time, as a :class:`float` value, according to the
93 event loop's internal clock.
94
95.. method:: call_later(delay, callback, *args)
96
97 Arrange for the *callback* to be called after the given *delay*
98 seconds (either an int or float).
99
100 A "handle" is returned: an opaque object with a :meth:`cancel` method
101 that can be used to cancel the call.
102
103 *callback* will be called exactly once per call to :meth:`call_later`.
104 If two callbacks are scheduled for exactly the same time, it is
105 undefined which will be called first.
106
107 The optional positional *args* will be passed to the callback when it
108 is called. If you want the callback to be called with some named
109 arguments, use a closure or :func:`functools.partial`.
110
111.. method:: call_at(when, callback, *args)
112
113 Arrange for the *callback* to be called at the given absolute timestamp
114 *when* (an int or float), using the same time reference as :meth:`time`.
115
116 This method's behavior is the same as :meth:`call_later`.
117
Antoine Pitroua30d82f2013-11-23 13:55:35 +0100118Creating connections
119^^^^^^^^^^^^^^^^^^^^
120
121.. method:: create_connection(protocol_factory, host=None, port=None, **options)
122
123 Create a streaming transport connection to a given Internet *host* and
124 *port*. *protocol_factory* must be a callable returning a
125 :ref:`protocol <protocol>` instance.
126
127 This method returns a :ref:`coroutine <coroutine>` which will try to
128 establish the connection in the background. When successful, the
129 coroutine returns a ``(transport, protocol)`` pair.
130
131 The chronological synopsis of the underlying operation is as follows:
132
133 #. The connection is established, and a :ref:`transport <transport>`
134 is created to represent it.
135
136 #. *protocol_factory* is called without arguments and must return a
137 :ref:`protocol <protocol>` instance.
138
139 #. The protocol instance is tied to the transport, and its
140 :meth:`connection_made` method is called.
141
142 #. The coroutine returns successfully with the ``(transport, protocol)``
143 pair.
144
145 The created transport is an implementation-dependent bidirectional stream.
146
147 .. note::
148 *protocol_factory* can be any kind of callable, not necessarily
149 a class. For example, if you want to use a pre-created
150 protocol instance, you can pass ``lambda: my_protocol``.
151
152 *options* are optional named arguments allowing to change how the
153 connection is created:
154
155 * *ssl*: if given and not false, a SSL/TLS transport is created
156 (by default a plain TCP transport is created). If *ssl* is
157 a :class:`ssl.SSLContext` object, this context is used to create
158 the transport; if *ssl* is :const:`True`, a context with some
159 unspecified default settings is used.
160
161 * *server_hostname*, is only for use together with *ssl*,
162 and sets or overrides the hostname that the target server's certificate
163 will be matched against. By default the value of the *host* argument
164 is used. If *host* is empty, there is no default and you must pass a
165 value for *server_hostname*. If *server_hostname* is an empty
166 string, hostname matching is disabled (which is a serious security
167 risk, allowing for man-in-the-middle-attacks).
168
169 * *family*, *proto*, *flags* are the optional address family, protocol
170 and flags to be passed through to getaddrinfo() for *host* resolution.
171 If given, these should all be integers from the corresponding
172 :mod:`socket` module constants.
173
174 * *sock*, if given, should be an existing, already connected
175 :class:`socket.socket` object to be used by the transport.
176 If *sock* is given, none of *host*, *port*, *family*, *proto*, *flags*
177 and *local_addr* should be specified.
178
179 * *local_addr*, if given, is a ``(local_host, local_port)`` tuple used
180 to bind the socket to locally. The *local_host* and *local_port*
181 are looked up using getaddrinfo(), similarly to *host* and *port*.
182
Antoine Pitroubba86822013-11-23 00:34:26 +0100183
184.. _protocol:
185
186Protocols
187---------
188
Antoine Pitroua035e1b2013-11-23 01:08:43 +0100189:mod:`asyncio` provides base classes that you can subclass to implement
190your network protocols. Those classes are used in conjunction with
191:ref:`transports <transport>` (see below): the protocol parses incoming
192data and asks for the writing of outgoing data, while the transport is
193responsible for the actual I/O and buffering.
194
195When subclassing a protocol class, it is recommended you override certain
196methods. Those methods are callbacks: they will be called by the transport
197on certain events (for example when some data is received); you shouldn't
198call them yourself, unless you are implementing a transport.
199
Antoine Pitrou74193af2013-11-23 01:21:11 +0100200.. note::
201 All callbacks have default implementations, which are empty. Therefore,
202 you only need to implement the callbacks for the events in which you
203 are interested.
204
Antoine Pitroua035e1b2013-11-23 01:08:43 +0100205
206Protocol classes
207^^^^^^^^^^^^^^^^
208
209.. class:: Protocol
210
211 The base class for implementing streaming protocols (for use with
212 e.g. TCP and SSL transports).
213
214.. class:: DatagramProtocol
215
216 The base class for implementing datagram protocols (for use with
217 e.g. UDP transports).
218
219.. class:: SubprocessProtocol
220
Antoine Pitrou74193af2013-11-23 01:21:11 +0100221 The base class for implementing protocols communicating with child
222 processes (through a set of unidirectional pipes).
Antoine Pitroua035e1b2013-11-23 01:08:43 +0100223
224
225Connection callbacks
226^^^^^^^^^^^^^^^^^^^^
227
228These callbacks may be called on :class:`Protocol` and
Antoine Pitrou74193af2013-11-23 01:21:11 +0100229:class:`SubprocessProtocol` instances:
Antoine Pitroua035e1b2013-11-23 01:08:43 +0100230
231.. method:: connection_made(transport)
232
233 Called when a connection is made.
234
235 The *transport* argument is the transport representing the
236 connection. You are responsible for storing it somewhere
237 (e.g. as an attribute) if you need to.
238
239.. method:: connection_lost(exc)
240
241 Called when the connection is lost or closed.
242
243 The argument is either an exception object or :const:`None`.
244 The latter means a regular EOF is received, or the connection was
245 aborted or closed by this side of the connection.
246
247:meth:`connection_made` and :meth:`connection_lost` are called exactly once
248per successful connection. All other callbacks will be called between those
249two methods, which allows for easier resource management in your protocol
250implementation.
251
Antoine Pitrou74193af2013-11-23 01:21:11 +0100252The following callbacks may be called only on :class:`SubprocessProtocol`
253instances:
254
255.. method:: pipe_data_received(fd, data)
256
257 Called when the child process writes data into its stdout or stderr pipe.
258 *fd* is the integer file descriptor of the pipe. *data* is a non-empty
259 bytes object containing the data.
260
261.. method:: pipe_connection_lost(fd, exc)
262
263 Called when one of the pipes communicating with the child process
264 is closed. *fd* is the integer file descriptor that was closed.
265
266.. method:: process_exited()
267
268 Called when the child process has exited.
269
Antoine Pitroua035e1b2013-11-23 01:08:43 +0100270
271Data reception callbacks
272^^^^^^^^^^^^^^^^^^^^^^^^
273
Antoine Pitrou74193af2013-11-23 01:21:11 +0100274Streaming protocols
275"""""""""""""""""""
276
277The following callbacks are called on :class:`Protocol` instances:
Antoine Pitroua035e1b2013-11-23 01:08:43 +0100278
279.. method:: data_received(data)
280
281 Called when some data is received. *data* is a non-empty bytes object
282 containing the incoming data.
283
284 .. note::
285 Whether the data is buffered, chunked or reassembled depends on
286 the transport. In general, you shouldn't rely on specific semantics
Antoine Pitrou74193af2013-11-23 01:21:11 +0100287 and instead make your parsing generic and flexible enough. However,
288 data is always received in the correct order.
Antoine Pitroua035e1b2013-11-23 01:08:43 +0100289
290.. method:: eof_received()
291
292 Calls when the other end signals it won't send any more data
293 (for example by calling :meth:`write_eof`, if the other end also uses
294 asyncio).
295
296 This method may return a false value (including None), in which case
297 the transport will close itself. Conversely, if this method returns a
298 true value, closing the transport is up to the protocol. Since the
299 default implementation returns None, it implicitly closes the connection.
300
301 .. note::
302 Some transports such as SSL don't support half-closed connections,
303 in which case returning true from this method will not prevent closing
304 the connection.
305
Antoine Pitroua035e1b2013-11-23 01:08:43 +0100306:meth:`data_received` can be called an arbitrary number of times during
307a connection. However, :meth:`eof_received` is called at most once
308and, if called, :meth:`data_received` won't be called after it.
309
Antoine Pitrou74193af2013-11-23 01:21:11 +0100310Datagram protocols
311""""""""""""""""""
312
313The following callbacks are called on :class:`DatagramProtocol` instances.
314
315.. method:: datagram_received(data, addr)
316
317 Called when a datagram is received. *data* is a bytes object containing
318 the incoming data. *addr* is the address of the peer sending the data;
319 the exact format depends on the transport.
320
321.. method:: error_received(exc)
322
323 Called when a previous send or receive operation raises an
324 :class:`OSError`. *exc* is the :class:`OSError` instance.
325
326 This method is called in rare conditions, when the transport (e.g. UDP)
327 detects that a datagram couldn't be delivered to its recipient.
328 In many conditions though, undeliverable datagrams will be silently
329 dropped.
330
Antoine Pitroua035e1b2013-11-23 01:08:43 +0100331
332Flow control callbacks
333^^^^^^^^^^^^^^^^^^^^^^
334
335These callbacks may be called on :class:`Protocol` and
Antoine Pitrou74193af2013-11-23 01:21:11 +0100336:class:`SubprocessProtocol` instances:
Antoine Pitroua035e1b2013-11-23 01:08:43 +0100337
338.. method:: pause_writing()
339
340 Called when the transport's buffer goes over the high-water mark.
341
342.. method:: resume_writing()
343
344 Called when the transport's buffer drains below the low-water mark.
345
346
347:meth:`pause_writing` and :meth:`resume_writing` calls are paired --
348:meth:`pause_writing` is called once when the buffer goes strictly over
349the high-water mark (even if subsequent writes increases the buffer size
350even more), and eventually :meth:`resume_writing` is called once when the
351buffer size reaches the low-water mark.
352
353.. note::
354 If the buffer size equals the high-water mark,
355 :meth:`pause_writing` is not called -- it must go strictly over.
356 Conversely, :meth:`resume_writing` is called when the buffer size is
357 equal or lower than the low-water mark. These end conditions
358 are important to ensure that things go as expected when either
359 mark is zero.
360
Antoine Pitroubba86822013-11-23 00:34:26 +0100361
362.. _transport:
363
364Transports
365----------
366
Antoine Pitrou4d1046c2013-11-23 12:50:52 +0100367Transports are classed provided by :mod:`asyncio` in order to abstract
368various kinds of communication channels. You generally won't instantiate
369a transport yourself; instead, you will call a :class:`EventLoop` method
370which will create the transport and try to initiate the underlying
371communication channel, calling you back when it succeeds.
372
373Once the communication channel is established, a transport is always
374paired with a :ref:`protocol <protocol>` instance. The protocol can
375then call the transport's methods for various purposes.
376
377:mod:`asyncio` currently implements transports for TCP, UDP, SSL, and
378subprocess pipes. The methods available on a transport depend on
379the transport's kind.
380
381Methods common to all transports
382^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
383
384.. method:: close(self)
385
386 Close the transport. If the transport has a buffer for outgoing
387 data, buffered data will be flushed asynchronously. No more data
388 will be received. After all buffered data is flushed, the
389 protocol's :meth:`connection_lost` method will be called with
390 :const:`None` as its argument.
391
392
393.. method:: get_extra_info(name, default=None)
394
395 Return optional transport information. *name* is a string representing
396 the piece of transport-specific information to get, *default* is the
397 value to return if the information doesn't exist.
398
399 This method allows transport implementations to easily expose
400 channel-specific information.
401
402Methods of readable streaming transports
403^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
404
405.. method:: pause_reading()
406
407 Pause the receiving end of the transport. No data will be passed to
408 the protocol's :meth:`data_received` method until meth:`resume_reading`
409 is called.
410
411.. method:: resume_reading()
412
413 Resume the receiving end. The protocol's :meth:`data_received` method
414 will be called once again if some data is available for reading.
415
416Methods of writable streaming transports
417^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
418
419.. method:: write(data)
420
421 Write some *data* bytes to the transport.
422
423 This method does not block; it buffers the data and arranges for it
424 to be sent out asynchronously.
425
426.. method:: writelines(list_of_data)
427
428 Write a list (or any iterable) of data bytes to the transport.
429 This is functionally equivalent to calling :meth:`write` on each
430 element yielded by the iterable, but may be implemented more efficiently.
431
432.. method:: write_eof()
433
434 Close the write end of the transport after flushing buffered data.
435 Data may still be received.
436
437 This method can raise :exc:`NotImplementedError` if the transport
438 (e.g. SSL) doesn't support half-closes.
439
440.. method:: can_write_eof()
441
442 Return :const:`True` if the transport supports :meth:`write_eof`,
443 :const:`False` if not.
444
445.. method:: abort()
446
447 Close the transport immediately, without waiting for pending operations
448 to complete. Buffered data will be lost. No more data will be received.
449 The protocol's :meth:`connection_lost` method will eventually be
450 called with :const:`None` as its argument.
451
452.. method:: set_write_buffer_limits(high=None, low=None)
453
454 Set the *high*- and *low*-water limits for write flow control.
455
456 These two values control when call the protocol's
457 :meth:`pause_writing` and :meth:`resume_writing` methods are called.
458 If specified, the low-water limit must be less than or equal to the
459 high-water limit. Neither *high* nor *low* can be negative.
460
461 The defaults are implementation-specific. If only the
462 high-water limit is given, the low-water limit defaults to a
463 implementation-specific value less than or equal to the
464 high-water limit. Setting *high* to zero forces *low* to zero as
465 well, and causes :meth:`pause_writing` to be called whenever the
466 buffer becomes non-empty. Setting *low* to zero causes
467 :meth:`resume_writing` to be called only once the buffer is empty.
468 Use of zero for either limit is generally sub-optimal as it
469 reduces opportunities for doing I/O and computation
470 concurrently.
471
472.. method:: get_write_buffer_size()
473
474 Return the current size of the output buffer used by the transport.
475
476Methods of datagram transports
477^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
478
479.. method:: sendto(data, addr=None)
480
481 Send the *data* bytes to the remote peer given by *addr* (a
482 transport-dependent target address). If *addr* is :const:`None`, the
483 data is sent to the target address given on transport creation.
484
485 This method does not block; it buffers the data and arranges for it
486 to be sent out asynchronously.
487
488.. method:: abort()
489
490 Close the transport immediately, without waiting for pending operations
491 to complete. Buffered data will be lost. No more data will be received.
492 The protocol's :meth:`connection_lost` method will eventually be
493 called with :const:`None` as its argument.
494
495Methods of subprocess transports
496^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
497
498.. method:: get_pid()
499
500 Return the subprocess process id as an integer.
501
502.. method:: get_returncode()
503
504 Return the subprocess returncode as an integer or :const:`None`
505 if it hasn't returned, similarly to the
506 :attr:`subprocess.Popen.returncode` attribute.
507
508.. method:: get_pipe_transport(fd)
509
510 Return the transport for the communication pipe correspondong to the
511 integer file descriptor *fd*. The return value can be a readable or
512 writable streaming transport, depending on the *fd*. If *fd* doesn't
513 correspond to a pipe belonging to this transport, :const:`None` is
514 returned.
515
516.. method:: send_signal(signal)
517
518 Send the *signal* number to the subprocess, as in
519 :meth:`subprocess.Popen.send_signal`.
520
521.. method:: terminate()
522
523 Ask the subprocess to stop, as in :meth:`subprocess.Popen.terminate`.
524 This method is an alias for the :meth:`close` method.
525
526 On POSIX systems, this method sends SIGTERM to the subprocess.
527 On Windows, the Windows API function TerminateProcess() is called to
528 stop the subprocess.
529
530.. method:: kill(self)
531
532 Kill the subprocess, as in :meth:`subprocess.Popen.kill`
533
534 On POSIX systems, the function sends SIGKILL to the subprocess.
535 On Windows, this method is an alias for :meth:`terminate`.
536
Antoine Pitroubba86822013-11-23 00:34:26 +0100537
Antoine Pitroua30d82f2013-11-23 13:55:35 +0100538.. _coroutine:
539
540Coroutines
541----------
542
543
Antoine Pitroubba86822013-11-23 00:34:26 +0100544.. _sync:
545
546Synchronization primitives
547--------------------------
548
549
550Examples
551--------
552
553A :class:`Protocol` implementing an echo server::
554
555 class EchoServer(asyncio.Protocol):
556
557 TIMEOUT = 5.0
558
559 def timeout(self):
560 print('connection timeout, closing.')
561 self.transport.close()
562
563 def connection_made(self, transport):
564 print('connection made')
565 self.transport = transport
566
567 # start 5 seconds timeout timer
568 self.h_timeout = asyncio.get_event_loop().call_later(
569 self.TIMEOUT, self.timeout)
570
571 def data_received(self, data):
572 print('data received: ', data.decode())
573 self.transport.write(b'Re: ' + data)
574
575 # restart timeout timer
576 self.h_timeout.cancel()
577 self.h_timeout = asyncio.get_event_loop().call_later(
578 self.TIMEOUT, self.timeout)
579
580 def eof_received(self):
581 pass
582
583 def connection_lost(self, exc):
584 print('connection lost:', exc)
585 self.h_timeout.cancel()
586