| Guido van Rossum | 7a46564 | 2013-11-22 11:47:22 -0800 | [diff] [blame] | 1 | :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 Rossum | f8d0ff9 | 2013-11-22 16:53:25 -0800 | [diff] [blame] | 9 | **Source code:** :source:`Lib/asyncio/` |
| 10 | |
| 11 | -------------- |
| Guido van Rossum | 7a46564 | 2013-11-22 11:47:22 -0800 | [diff] [blame] | 12 | |
| Antoine Pitrou | bba8682 | 2013-11-23 00:34:26 +0100 | [diff] [blame] | 13 | This module provides infrastructure for writing single-threaded concurrent |
| 14 | code using coroutines, multiplexing I/O access over sockets and other |
| 15 | resources, running network clients and servers, and other related primitives. |
| Guido van Rossum | 7a46564 | 2013-11-22 11:47:22 -0800 | [diff] [blame] | 16 | |
| Antoine Pitrou | bba8682 | 2013-11-23 00:34:26 +0100 | [diff] [blame] | 17 | Here 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 Rossum | f0f5d38 | 2013-11-22 15:45:02 -0800 | [diff] [blame] | 39 | * 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 Pitrou | bba8682 | 2013-11-23 00:34:26 +0100 | [diff] [blame] | 43 | |
| 44 | Disclaimer |
| 45 | ---------- |
| Guido van Rossum | 7a46564 | 2013-11-22 11:47:22 -0800 | [diff] [blame] | 46 | |
| 47 | Full documentation is not yet ready; we hope to have it written |
| 48 | before Python 3.4 leaves beta. Until then, the best reference is |
| 49 | :PEP:`3156`. For a motivational primer on transports and protocols, |
| 50 | see :PEP:`3153`. |
| Antoine Pitrou | bba8682 | 2013-11-23 00:34:26 +0100 | [diff] [blame] | 51 | |
| 52 | |
| 53 | .. XXX should the asyncio documentation come in several pages, as for logging? |
| 54 | |
| 55 | |
| 56 | .. _event-loop: |
| 57 | |
| 58 | Event loops |
| 59 | ----------- |
| 60 | |
| 61 | |
| 62 | .. _protocol: |
| 63 | |
| 64 | Protocols |
| 65 | --------- |
| 66 | |
| Antoine Pitrou | a035e1b | 2013-11-23 01:08:43 +0100 | [diff] [blame] | 67 | :mod:`asyncio` provides base classes that you can subclass to implement |
| 68 | your network protocols. Those classes are used in conjunction with |
| 69 | :ref:`transports <transport>` (see below): the protocol parses incoming |
| 70 | data and asks for the writing of outgoing data, while the transport is |
| 71 | responsible for the actual I/O and buffering. |
| 72 | |
| 73 | When subclassing a protocol class, it is recommended you override certain |
| 74 | methods. Those methods are callbacks: they will be called by the transport |
| 75 | on certain events (for example when some data is received); you shouldn't |
| 76 | call them yourself, unless you are implementing a transport. |
| 77 | |
| Antoine Pitrou | 74193af | 2013-11-23 01:21:11 +0100 | [diff] [blame] | 78 | .. note:: |
| 79 | All callbacks have default implementations, which are empty. Therefore, |
| 80 | you only need to implement the callbacks for the events in which you |
| 81 | are interested. |
| 82 | |
| Antoine Pitrou | a035e1b | 2013-11-23 01:08:43 +0100 | [diff] [blame] | 83 | |
| 84 | Protocol classes |
| 85 | ^^^^^^^^^^^^^^^^ |
| 86 | |
| 87 | .. class:: Protocol |
| 88 | |
| 89 | The base class for implementing streaming protocols (for use with |
| 90 | e.g. TCP and SSL transports). |
| 91 | |
| 92 | .. class:: DatagramProtocol |
| 93 | |
| 94 | The base class for implementing datagram protocols (for use with |
| 95 | e.g. UDP transports). |
| 96 | |
| 97 | .. class:: SubprocessProtocol |
| 98 | |
| Antoine Pitrou | 74193af | 2013-11-23 01:21:11 +0100 | [diff] [blame] | 99 | The base class for implementing protocols communicating with child |
| 100 | processes (through a set of unidirectional pipes). |
| Antoine Pitrou | a035e1b | 2013-11-23 01:08:43 +0100 | [diff] [blame] | 101 | |
| 102 | |
| 103 | Connection callbacks |
| 104 | ^^^^^^^^^^^^^^^^^^^^ |
| 105 | |
| 106 | These callbacks may be called on :class:`Protocol` and |
| Antoine Pitrou | 74193af | 2013-11-23 01:21:11 +0100 | [diff] [blame] | 107 | :class:`SubprocessProtocol` instances: |
| Antoine Pitrou | a035e1b | 2013-11-23 01:08:43 +0100 | [diff] [blame] | 108 | |
| 109 | .. method:: connection_made(transport) |
| 110 | |
| 111 | Called when a connection is made. |
| 112 | |
| 113 | The *transport* argument is the transport representing the |
| 114 | connection. You are responsible for storing it somewhere |
| 115 | (e.g. as an attribute) if you need to. |
| 116 | |
| 117 | .. method:: connection_lost(exc) |
| 118 | |
| 119 | Called when the connection is lost or closed. |
| 120 | |
| 121 | The argument is either an exception object or :const:`None`. |
| 122 | The latter means a regular EOF is received, or the connection was |
| 123 | aborted or closed by this side of the connection. |
| 124 | |
| 125 | :meth:`connection_made` and :meth:`connection_lost` are called exactly once |
| 126 | per successful connection. All other callbacks will be called between those |
| 127 | two methods, which allows for easier resource management in your protocol |
| 128 | implementation. |
| 129 | |
| Antoine Pitrou | 74193af | 2013-11-23 01:21:11 +0100 | [diff] [blame] | 130 | The following callbacks may be called only on :class:`SubprocessProtocol` |
| 131 | instances: |
| 132 | |
| 133 | .. method:: pipe_data_received(fd, data) |
| 134 | |
| 135 | Called when the child process writes data into its stdout or stderr pipe. |
| 136 | *fd* is the integer file descriptor of the pipe. *data* is a non-empty |
| 137 | bytes object containing the data. |
| 138 | |
| 139 | .. method:: pipe_connection_lost(fd, exc) |
| 140 | |
| 141 | Called when one of the pipes communicating with the child process |
| 142 | is closed. *fd* is the integer file descriptor that was closed. |
| 143 | |
| 144 | .. method:: process_exited() |
| 145 | |
| 146 | Called when the child process has exited. |
| 147 | |
| Antoine Pitrou | a035e1b | 2013-11-23 01:08:43 +0100 | [diff] [blame] | 148 | |
| 149 | Data reception callbacks |
| 150 | ^^^^^^^^^^^^^^^^^^^^^^^^ |
| 151 | |
| Antoine Pitrou | 74193af | 2013-11-23 01:21:11 +0100 | [diff] [blame] | 152 | Streaming protocols |
| 153 | """"""""""""""""""" |
| 154 | |
| 155 | The following callbacks are called on :class:`Protocol` instances: |
| Antoine Pitrou | a035e1b | 2013-11-23 01:08:43 +0100 | [diff] [blame] | 156 | |
| 157 | .. method:: data_received(data) |
| 158 | |
| 159 | Called when some data is received. *data* is a non-empty bytes object |
| 160 | containing the incoming data. |
| 161 | |
| 162 | .. note:: |
| 163 | Whether the data is buffered, chunked or reassembled depends on |
| 164 | the transport. In general, you shouldn't rely on specific semantics |
| Antoine Pitrou | 74193af | 2013-11-23 01:21:11 +0100 | [diff] [blame] | 165 | and instead make your parsing generic and flexible enough. However, |
| 166 | data is always received in the correct order. |
| Antoine Pitrou | a035e1b | 2013-11-23 01:08:43 +0100 | [diff] [blame] | 167 | |
| 168 | .. method:: eof_received() |
| 169 | |
| 170 | Calls when the other end signals it won't send any more data |
| 171 | (for example by calling :meth:`write_eof`, if the other end also uses |
| 172 | asyncio). |
| 173 | |
| 174 | This method may return a false value (including None), in which case |
| 175 | the transport will close itself. Conversely, if this method returns a |
| 176 | true value, closing the transport is up to the protocol. Since the |
| 177 | default implementation returns None, it implicitly closes the connection. |
| 178 | |
| 179 | .. note:: |
| 180 | Some transports such as SSL don't support half-closed connections, |
| 181 | in which case returning true from this method will not prevent closing |
| 182 | the connection. |
| 183 | |
| Antoine Pitrou | a035e1b | 2013-11-23 01:08:43 +0100 | [diff] [blame] | 184 | :meth:`data_received` can be called an arbitrary number of times during |
| 185 | a connection. However, :meth:`eof_received` is called at most once |
| 186 | and, if called, :meth:`data_received` won't be called after it. |
| 187 | |
| Antoine Pitrou | 74193af | 2013-11-23 01:21:11 +0100 | [diff] [blame] | 188 | Datagram protocols |
| 189 | """""""""""""""""" |
| 190 | |
| 191 | The following callbacks are called on :class:`DatagramProtocol` instances. |
| 192 | |
| 193 | .. method:: datagram_received(data, addr) |
| 194 | |
| 195 | Called when a datagram is received. *data* is a bytes object containing |
| 196 | the incoming data. *addr* is the address of the peer sending the data; |
| 197 | the exact format depends on the transport. |
| 198 | |
| 199 | .. method:: error_received(exc) |
| 200 | |
| 201 | Called when a previous send or receive operation raises an |
| 202 | :class:`OSError`. *exc* is the :class:`OSError` instance. |
| 203 | |
| 204 | This method is called in rare conditions, when the transport (e.g. UDP) |
| 205 | detects that a datagram couldn't be delivered to its recipient. |
| 206 | In many conditions though, undeliverable datagrams will be silently |
| 207 | dropped. |
| 208 | |
| Antoine Pitrou | a035e1b | 2013-11-23 01:08:43 +0100 | [diff] [blame] | 209 | |
| 210 | Flow control callbacks |
| 211 | ^^^^^^^^^^^^^^^^^^^^^^ |
| 212 | |
| 213 | These callbacks may be called on :class:`Protocol` and |
| Antoine Pitrou | 74193af | 2013-11-23 01:21:11 +0100 | [diff] [blame] | 214 | :class:`SubprocessProtocol` instances: |
| Antoine Pitrou | a035e1b | 2013-11-23 01:08:43 +0100 | [diff] [blame] | 215 | |
| 216 | .. method:: pause_writing() |
| 217 | |
| 218 | Called when the transport's buffer goes over the high-water mark. |
| 219 | |
| 220 | .. method:: resume_writing() |
| 221 | |
| 222 | Called when the transport's buffer drains below the low-water mark. |
| 223 | |
| 224 | |
| 225 | :meth:`pause_writing` and :meth:`resume_writing` calls are paired -- |
| 226 | :meth:`pause_writing` is called once when the buffer goes strictly over |
| 227 | the high-water mark (even if subsequent writes increases the buffer size |
| 228 | even more), and eventually :meth:`resume_writing` is called once when the |
| 229 | buffer size reaches the low-water mark. |
| 230 | |
| 231 | .. note:: |
| 232 | If the buffer size equals the high-water mark, |
| 233 | :meth:`pause_writing` is not called -- it must go strictly over. |
| 234 | Conversely, :meth:`resume_writing` is called when the buffer size is |
| 235 | equal or lower than the low-water mark. These end conditions |
| 236 | are important to ensure that things go as expected when either |
| 237 | mark is zero. |
| 238 | |
| Antoine Pitrou | bba8682 | 2013-11-23 00:34:26 +0100 | [diff] [blame] | 239 | |
| 240 | .. _transport: |
| 241 | |
| 242 | Transports |
| 243 | ---------- |
| 244 | |
| Antoine Pitrou | 4d1046c | 2013-11-23 12:50:52 +0100 | [diff] [blame^] | 245 | Transports are classed provided by :mod:`asyncio` in order to abstract |
| 246 | various kinds of communication channels. You generally won't instantiate |
| 247 | a transport yourself; instead, you will call a :class:`EventLoop` method |
| 248 | which will create the transport and try to initiate the underlying |
| 249 | communication channel, calling you back when it succeeds. |
| 250 | |
| 251 | Once the communication channel is established, a transport is always |
| 252 | paired with a :ref:`protocol <protocol>` instance. The protocol can |
| 253 | then call the transport's methods for various purposes. |
| 254 | |
| 255 | :mod:`asyncio` currently implements transports for TCP, UDP, SSL, and |
| 256 | subprocess pipes. The methods available on a transport depend on |
| 257 | the transport's kind. |
| 258 | |
| 259 | Methods common to all transports |
| 260 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 261 | |
| 262 | .. method:: close(self) |
| 263 | |
| 264 | Close the transport. If the transport has a buffer for outgoing |
| 265 | data, buffered data will be flushed asynchronously. No more data |
| 266 | will be received. After all buffered data is flushed, the |
| 267 | protocol's :meth:`connection_lost` method will be called with |
| 268 | :const:`None` as its argument. |
| 269 | |
| 270 | |
| 271 | .. method:: get_extra_info(name, default=None) |
| 272 | |
| 273 | Return optional transport information. *name* is a string representing |
| 274 | the piece of transport-specific information to get, *default* is the |
| 275 | value to return if the information doesn't exist. |
| 276 | |
| 277 | This method allows transport implementations to easily expose |
| 278 | channel-specific information. |
| 279 | |
| 280 | Methods of readable streaming transports |
| 281 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 282 | |
| 283 | .. method:: pause_reading() |
| 284 | |
| 285 | Pause the receiving end of the transport. No data will be passed to |
| 286 | the protocol's :meth:`data_received` method until meth:`resume_reading` |
| 287 | is called. |
| 288 | |
| 289 | .. method:: resume_reading() |
| 290 | |
| 291 | Resume the receiving end. The protocol's :meth:`data_received` method |
| 292 | will be called once again if some data is available for reading. |
| 293 | |
| 294 | Methods of writable streaming transports |
| 295 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 296 | |
| 297 | .. method:: write(data) |
| 298 | |
| 299 | Write some *data* bytes to the transport. |
| 300 | |
| 301 | This method does not block; it buffers the data and arranges for it |
| 302 | to be sent out asynchronously. |
| 303 | |
| 304 | .. method:: writelines(list_of_data) |
| 305 | |
| 306 | Write a list (or any iterable) of data bytes to the transport. |
| 307 | This is functionally equivalent to calling :meth:`write` on each |
| 308 | element yielded by the iterable, but may be implemented more efficiently. |
| 309 | |
| 310 | .. method:: write_eof() |
| 311 | |
| 312 | Close the write end of the transport after flushing buffered data. |
| 313 | Data may still be received. |
| 314 | |
| 315 | This method can raise :exc:`NotImplementedError` if the transport |
| 316 | (e.g. SSL) doesn't support half-closes. |
| 317 | |
| 318 | .. method:: can_write_eof() |
| 319 | |
| 320 | Return :const:`True` if the transport supports :meth:`write_eof`, |
| 321 | :const:`False` if not. |
| 322 | |
| 323 | .. method:: abort() |
| 324 | |
| 325 | Close the transport immediately, without waiting for pending operations |
| 326 | to complete. Buffered data will be lost. No more data will be received. |
| 327 | The protocol's :meth:`connection_lost` method will eventually be |
| 328 | called with :const:`None` as its argument. |
| 329 | |
| 330 | .. method:: set_write_buffer_limits(high=None, low=None) |
| 331 | |
| 332 | Set the *high*- and *low*-water limits for write flow control. |
| 333 | |
| 334 | These two values control when call the protocol's |
| 335 | :meth:`pause_writing` and :meth:`resume_writing` methods are called. |
| 336 | If specified, the low-water limit must be less than or equal to the |
| 337 | high-water limit. Neither *high* nor *low* can be negative. |
| 338 | |
| 339 | The defaults are implementation-specific. If only the |
| 340 | high-water limit is given, the low-water limit defaults to a |
| 341 | implementation-specific value less than or equal to the |
| 342 | high-water limit. Setting *high* to zero forces *low* to zero as |
| 343 | well, and causes :meth:`pause_writing` to be called whenever the |
| 344 | buffer becomes non-empty. Setting *low* to zero causes |
| 345 | :meth:`resume_writing` to be called only once the buffer is empty. |
| 346 | Use of zero for either limit is generally sub-optimal as it |
| 347 | reduces opportunities for doing I/O and computation |
| 348 | concurrently. |
| 349 | |
| 350 | .. method:: get_write_buffer_size() |
| 351 | |
| 352 | Return the current size of the output buffer used by the transport. |
| 353 | |
| 354 | Methods of datagram transports |
| 355 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 356 | |
| 357 | .. method:: sendto(data, addr=None) |
| 358 | |
| 359 | Send the *data* bytes to the remote peer given by *addr* (a |
| 360 | transport-dependent target address). If *addr* is :const:`None`, the |
| 361 | data is sent to the target address given on transport creation. |
| 362 | |
| 363 | This method does not block; it buffers the data and arranges for it |
| 364 | to be sent out asynchronously. |
| 365 | |
| 366 | .. method:: abort() |
| 367 | |
| 368 | Close the transport immediately, without waiting for pending operations |
| 369 | to complete. Buffered data will be lost. No more data will be received. |
| 370 | The protocol's :meth:`connection_lost` method will eventually be |
| 371 | called with :const:`None` as its argument. |
| 372 | |
| 373 | Methods of subprocess transports |
| 374 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 375 | |
| 376 | .. method:: get_pid() |
| 377 | |
| 378 | Return the subprocess process id as an integer. |
| 379 | |
| 380 | .. method:: get_returncode() |
| 381 | |
| 382 | Return the subprocess returncode as an integer or :const:`None` |
| 383 | if it hasn't returned, similarly to the |
| 384 | :attr:`subprocess.Popen.returncode` attribute. |
| 385 | |
| 386 | .. method:: get_pipe_transport(fd) |
| 387 | |
| 388 | Return the transport for the communication pipe correspondong to the |
| 389 | integer file descriptor *fd*. The return value can be a readable or |
| 390 | writable streaming transport, depending on the *fd*. If *fd* doesn't |
| 391 | correspond to a pipe belonging to this transport, :const:`None` is |
| 392 | returned. |
| 393 | |
| 394 | .. method:: send_signal(signal) |
| 395 | |
| 396 | Send the *signal* number to the subprocess, as in |
| 397 | :meth:`subprocess.Popen.send_signal`. |
| 398 | |
| 399 | .. method:: terminate() |
| 400 | |
| 401 | Ask the subprocess to stop, as in :meth:`subprocess.Popen.terminate`. |
| 402 | This method is an alias for the :meth:`close` method. |
| 403 | |
| 404 | On POSIX systems, this method sends SIGTERM to the subprocess. |
| 405 | On Windows, the Windows API function TerminateProcess() is called to |
| 406 | stop the subprocess. |
| 407 | |
| 408 | .. method:: kill(self) |
| 409 | |
| 410 | Kill the subprocess, as in :meth:`subprocess.Popen.kill` |
| 411 | |
| 412 | On POSIX systems, the function sends SIGKILL to the subprocess. |
| 413 | On Windows, this method is an alias for :meth:`terminate`. |
| 414 | |
| Antoine Pitrou | bba8682 | 2013-11-23 00:34:26 +0100 | [diff] [blame] | 415 | |
| 416 | .. _sync: |
| 417 | |
| 418 | Synchronization primitives |
| 419 | -------------------------- |
| 420 | |
| 421 | |
| 422 | Examples |
| 423 | -------- |
| 424 | |
| 425 | A :class:`Protocol` implementing an echo server:: |
| 426 | |
| 427 | class EchoServer(asyncio.Protocol): |
| 428 | |
| 429 | TIMEOUT = 5.0 |
| 430 | |
| 431 | def timeout(self): |
| 432 | print('connection timeout, closing.') |
| 433 | self.transport.close() |
| 434 | |
| 435 | def connection_made(self, transport): |
| 436 | print('connection made') |
| 437 | self.transport = transport |
| 438 | |
| 439 | # start 5 seconds timeout timer |
| 440 | self.h_timeout = asyncio.get_event_loop().call_later( |
| 441 | self.TIMEOUT, self.timeout) |
| 442 | |
| 443 | def data_received(self, data): |
| 444 | print('data received: ', data.decode()) |
| 445 | self.transport.write(b'Re: ' + data) |
| 446 | |
| 447 | # restart timeout timer |
| 448 | self.h_timeout.cancel() |
| 449 | self.h_timeout = asyncio.get_event_loop().call_later( |
| 450 | self.TIMEOUT, self.timeout) |
| 451 | |
| 452 | def eof_received(self): |
| 453 | pass |
| 454 | |
| 455 | def connection_lost(self, exc): |
| 456 | print('connection lost:', exc) |
| 457 | self.h_timeout.cancel() |
| 458 | |