A single argument in a list. arg is a raw string of the argument name, annotation is its annotation, such as a Str or Name node.
type_comment is an optional string with the type annotation as a comment


type_comment is an optional string with the type annotation as a comment


An assertion. test holds the condition, such as a Compare node. msg holds the failure message.


An assignment. targets is a list of nodes, and value is a single node.
Multiple nodes in targets represents assigning the same value to each. Unpacking is represented by putting a Tuple or List within targets.
type_comment is an optional string with the type annotation as a comment.


type_comment is an optional string with the type annotation as a comment.


This is the base of all AST node classes. The actual node classes are derived from the Parser/Python.asdl file, which is reproduced below. They are defined in the _ast C module and re-exported in ast.
There is one class defined for each left-hand side symbol in the abstract grammar (for example, ast.stmt or ast.expr). In addition, there is one class defined for each constructor on the right-hand side; these classes inherit from the classes for the left-hand side trees. For example, ast.BinOp inherits from ast.expr. For production rules with alternatives (aka “sums”), the left-hand side class is abstract: only instances of specific constructor nodes are ever created.
Each concrete class has an attribute _fields which gives the names of all child nodes.
Each instance of a concrete class has one attribute for each child node, of the type as defined in the grammar. For example, ast.BinOp instances have an attribute left of type ast.expr.
If these attributes are marked as optional in the grammar (using a question mark), the value might be None. If the attributes can have zero-or-more values (marked with an asterisk), the values are represented as Python lists. All possible attributes must be present and have valid values when compiling an AST with compile().
Instances of ast.expr and ast.stmt subclasses have lineno, col_offset, lineno, and col_offset attributes. The lineno and end_lineno are the first and last line numbers of source text span (1-indexed so the first line is line 1) and the col_offset and end_col_offset are the corresponding UTF-8 byte offsets of the first and last tokens that generated the node. The UTF-8 offset is recorded because the parser uses UTF-8 internally.
Note that the end positions are not required by the compiler and are therefore optional. The end offset is after the last symbol, for example one can get the source segment of a one-line expression node using source_line[node.col_offset : node.end_col_offset].
The constructor of a class ast.T parses its arguments as follows:
For example, to create and populate an ast.UnaryOp node, you could use
or the more compact


Instances of ast.expr and ast.stmt subclasses have lineno, col_offset, lineno, and col_offset attributes. The lineno and end_lineno are the first and last line numbers of source text span (1-indexed so the first line is line 1) and the col_offset and end_col_offset are the corresponding UTF-8 byte offsets of the first and last tokens that generated the node. The UTF-8 offset is recorded because the parser uses UTF-8 internally.
Note that the end positions are not required by the compiler and are therefore optional. The end offset is after the last symbol, for example one can get the source segment of a one-line expression node using source_line[node.col_offset : node.end_col_offset].


Each concrete class has an attribute _fields which gives the names of all child nodes.
Each instance of a concrete class has one attribute for each child node, of the type as defined in the grammar. For example, ast.BinOp instances have an attribute left of type ast.expr.
If these attributes are marked as optional in the grammar (using a question mark), the value might be None. If the attributes can have zero-or-more values (marked with an asterisk), the values are represented as Python lists. All possible attributes must be present and have valid values when compiling an AST with compile().


async for loops and async with context managers. They have the same fields as For and With, respectively. Only valid in the body of an AsyncFunctionDef.


An async def function definition. Has the same fields as FunctionDef.


Attribute access, e.g. d.keys. value is a node, typically a Name. attr is a bare string giving the name of the attribute, and ctx is Load, Store or Del according to how the attribute is acted on.


Augmented assignment, such as a += 1. In the following example, target is a Name node for x (with the Store context), op is Add, and value is a Constant with value for 1.
The target attribute connot be of class Tuple or List, unlike the targets of Assign.


An await expression. value is what it waits for. Only valid in the body of an AsyncFunctionDef.


A binary operation (like addition or division). op is the operator, and left and right are any expression nodes.


A boolean operation, ‘or’ or ‘and’. op is Or or And. values are the values involved. Consecutive operations with the same operator, such as a or b or c, are collapsed into one node with several values.
This doesn’t include not, which is a UnaryOp.


A function call. func is the function, which will often be a Name or Attribute object. Of the arguments:
When creating a Call node, args and keywords are required, but they can be empty lists. starargs and kwargs are optional.


A comparison of two or more values. left is the first value in the comparison, ops the list of operators, and comparators the list of values after the first element in the comparison.


One for clause in a comprehension. target is the reference to use for each element - typically a Name or Tuple node. iter is the object to iterate over. ifs is a list of test expressions: each for clause can have multiple ifs.
is_async indicates a comprehension is asynchronous (using an async for instead of for). The value is an integer (0 or 1).


A constant value. The value attribute of the Constant literal contains the Python object it represents. The values represented can be simple types such as a number, string or None, but also immutable container types (tuples and frozensets) if all of their elements are constant.


Copy source location (lineno, col_offset, end_lineno, and end_col_offset) from old_node to new_node if possible, and return new_node.


Variable references can be used to load the value of a variable, to assign a new value to it, or to delete it. Variable references are given a context to distinguish these cases.


Represents a del statement. targets is a list of nodes, such as Name, Attribute or Subscript nodes.


A dictionary. keys and values hold lists of nodes representing the keys and the values respectively, in matching order (what would be returned when calling dictionary.keys() and dictionary.values()).
When doing dictionary unpacking using dictionary literals the expression to be expanded goes in the values list, with a None at the corresponding position in keys.


List and set comprehensions, generator expressions, and dictionary comprehensions. elt (or key and value) is a single node representing the part that will be evaluated for each item.
generators is a list of comprehension nodes.


Return a formatted dump of the tree in node. This is mainly useful for debugging purposes. If annotate_fields is true (by default), the returned string will show the names and the values for fields. If annotate_fields is false, the result string will be more compact by omitting unambiguous field names. Attributes such as line numbers and column offsets are not dumped by default. If this is wanted, include_attributes can be set to true.
If indent is a non-negative integer or string, then the tree will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the single line representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level.
Changed in version 3.9: Added the indent option.


A single except clause. type is the exception type it will match, typically a Name node (or None for a catch-all except: clause). name is a raw string for the name to hold the exception, or None if the clause doesn’t have as foo. body is a list of nodes.


When an expression, such as a function call, appears as a statement by itself with its return value not used or stored, it is wrapped in this container. value holds one of the other nodes in this section, a Constant, a Name, a Lambda, a Yield or YieldFrom node.


When you compile a node tree with compile(), the compiler expects lineno and col_offset attributes for every node that supports them. This is rather tedious to fill in for generated nodes, so this helper adds these attributes recursively where not already set, by setting them to the values of the parent node. It works recursively starting at node.


A for loop. target holds the variable(s) the loop assigns to, as a single Name, Tuple or List node. iter holds the item to be looped over, again as a single node. body and orelse contain lists of nodes to execute. Those in orelse are executed if the loop finishes normally, rather than via a break statement.
type_comment is an optional string with the type annotation as a comment.


type_comment is an optional string with the type annotation as a comment.


Node representing a single formatting field in an f-string. If the string contains a single formatting field and nothing else the node can be isolated otherwise it appears in JoinedStr.
conversion is an integer:


A function definition.
type_comment is an optional string with the type annotation as a comment.


Return the docstring of the given node (which must be a FunctionDef, AsyncFunctionDef, ClassDef, or Module node), or None if it has no docstring. If clean is true, clean up the docstring’s indentation with inspect.cleandoc().
Changed in version 3.5: AsyncFunctionDef is now supported.


Get source code segment of the source that generated node. If some location information (lineno, end_lineno, col_offset, or end_col_offset) is missing, return None.
If padded is True, the first line of a multi-line statement will be padded with spaces to match its original position.
New in version 3.8.


global and nonlocal statements. names is a list of raw strings.


An if statement. test holds a single node, such as a Compare node. body and orelse each hold a list of nodes.
elif clauses don’t have a special representation in the AST, but rather appear as extra If nodes within the orelse section of the previous one.


An expression such as a if b else c. Each field holds a single node, so in the following example, all three are Name nodes.


An import statement. names is a list of alias nodes.


Represents from x import y. module is a raw string of the ‘from’ name, without any leading dots, or None for statements such as from . import foo. level is an integer holding the level of the relative import (0 means absolute import).


Increment the line number and end line number of each node in the tree starting at node by n. This is useful to “move code” to a different location in a file.


Unary operator tokens. Not is the not keyword, Invert is the ~ operator.


Yield all direct child nodes of node, that is, all fields that are nodes and all items of fields that are lists of nodes.


Yield a tuple of (fieldname, value) for each field in node._fields that is present on node.


An f-string, comprising a series of FormattedValue and Constant nodes.


A keyword argument to a function call or class definition. arg is a raw string of the parameter name, value is a node to pass in.


lambda is a minimal function definition that can be used inside an expression. Unlike FunctionDef, body holds a single node.


A list or tuple. elts holds a list of nodes representing the elements. ctx is Store if the container is an assignment target (i.e. (x,y)=something), and Load otherwise.


List and set comprehensions, generator expressions, and dictionary comprehensions. elt (or key and value) is a single node representing the part that will be evaluated for each item.
generators is a list of comprehension nodes.


Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.
This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.
Warning
It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler.
Changed in version 3.2: Now allows bytes and set literals.
Changed in version 3.9: Now supports creating empty sets with 'set()'.


Variable references can be used to load the value of a variable, to assign a new value to it, or to delete it. Variable references are given a context to distinguish these cases.


A variable name. id holds the name as a string, and ctx is one of the following types.


A named expression. This AST node is produced by the assignment expressions operator (also known as the walrus operator). As opposed to the Assign node in which the first argument can be multiple nodes, in this case both target and value must be single nodes.


A NodeVisitor subclass that walks the abstract syntax tree and allows modification of nodes.
The NodeTransformer will walk the AST and use the return value of the visitor methods to replace or remove the old node. If the return value of the visitor method is None, the node will be removed from its location, otherwise it is replaced with the return value. The return value may be the original node in which case no replacement takes place.
Here is an example transformer that rewrites all occurrences of name lookups (foo) to data['foo']:
Keep in mind that if the node you’re operating on has child nodes you must either transform the child nodes yourself or call the generic_visit() method for the node first.
For nodes that were part of a collection of statements (that applies to all statement nodes), the visitor may also return a list of nodes rather than just a single node.
If NodeTransformer introduces new nodes (that weren’t part of original tree) without giving them location information (such as lineno), fix_missing_locations() should be called with the new sub-tree to recalculate the location information:
Usually you use the transformer like this:


A node visitor base class that walks the abstract syntax tree and calls a visitor function for every node found. This function may return a value which is forwarded by the visit() method.
This class is meant to be subclassed, with the subclass adding visitor methods.
Visit a node. The default implementation calls the method called self.visit_classname where classname is the name of the node class, or generic_visit() if that method doesn’t exist.
This visitor calls visit() on all children of the node.
Note that child nodes of nodes that have a custom visitor method won’t be visited unless the visitor calls generic_visit() or visits them itself.
Don’t use the NodeVisitor if you want to apply changes to nodes during traversal. For this a special visitor exists (NodeTransformer) that allows modifications.
Deprecated since version 3.8: Methods visit_Num(), visit_Str(), visit_Bytes(), visit_NameConstant() and visit_Ellipsis() are deprecated now and will not be called in future Python versions. Add the visit_Constant() method to handle all constant nodes.


This visitor calls visit() on all children of the node.
Note that child nodes of nodes that have a custom visitor method won’t be visited unless the visitor calls generic_visit() or visits them itself.


Visit a node. The default implementation calls the method called self.visit_classname where classname is the name of the node class, or generic_visit() if that method doesn’t exist.


global and nonlocal statements. names is a list of raw strings.


Unary operator tokens. Not is the not keyword, Invert is the ~ operator.


Parse the source into an AST node. Equivalent to compile(source,
filename, mode, ast.PyCF_ONLY_AST).
If type_comments=True is given, the parser is modified to check and return type comments as specified by PEP 484 and PEP 526. This is equivalent to adding ast.PyCF_TYPE_COMMENTS to the flags passed to compile(). This will report syntax errors for misplaced type comments. Without this flag, type comments will be ignored, and the type_comment field on selected AST nodes will always be None. In addition, the locations of # type:
ignore comments will be returned as the type_ignores attribute of Module (otherwise it is always an empty list).
In addition, if mode is 'func_type', the input syntax is modified to correspond to PEP 484 “signature type comments”, e.g. (str, int) -> List[str].
Also, setting feature_version to a tuple (major, minor) will attempt to parse using that Python version’s grammar. Currently major must equal to 3. For example, setting feature_version=(3, 4) will allow the use of async and await as variable names. The lowest supported version is (3, 4); the highest is sys.version_info[0:2].
Warning
It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler.
Changed in version 3.8: Added type_comments, mode='func_type' and feature_version.


Enables support for top-level await, async for, async with and async comprehensions.
New in version 3.8.


Generates and returns an abstract syntax tree instead of returning a compiled code object.


Enables support for PEP 484 and PEP 526 style type comments (# type: <type>, # type: ignore <stuff>).
New in version 3.8.


A raise statement. exc is the exception object to be raised, normally a Call or Name, or None for a standalone raise. cause is the optional part for y in raise x from y.


A set. elts holds a list of nodes representing the set’s elements.


List and set comprehensions, generator expressions, and dictionary comprehensions. elt (or key and value) is a single node representing the part that will be evaluated for each item.
generators is a list of comprehension nodes.


Regular slicing (on the form lower:upper or lower:upper:step). Can occur only inside the slice field of Subscript, either directly or as an element of Tuple.


A *var variable reference. value holds the variable, typically a Name node. This type must be used when building a Call node with *args.


Variable references can be used to load the value of a variable, to assign a new value to it, or to delete it. Variable references are given a context to distinguish these cases.


A subscript, such as l[1]. value is the subscripted object (usually sequence or mapping). slice is an index, slice or key. It can be a Tuple and contain a Slice. ctx is Load, Store or Del according to the action performed with the subscript.


try blocks. All attributes are list of nodes to execute, except for handlers, which is a list of ExceptHandler nodes.


A list or tuple. elts holds a list of nodes representing the elements. ctx is Store if the container is an assignment target (i.e. (x,y)=something), and Load otherwise.


A unary operation. op is the operator, and operand any expression node.


Unparse an ast.AST object and generate a string with code that would produce an equivalent ast.AST object if parsed back with ast.parse().
Warning
The produced code string will not necessarily be equal to the original code that generated the ast.AST object (without any compiler optimizations, such as constant tuples/frozensets).
Warning
Trying to unparse a highly complex expression would result with RecursionError.
New in version 3.9.


Recursively yield all descendant nodes in the tree starting at node (including node itself), in no specified order. This is useful if you only want to modify nodes in place and don’t care about the context.


A while loop. test holds the condition, such as a Compare node.


A with block. items is a list of withitem nodes representing the context managers, and body is the indented block inside the context.
type_comment is an optional string with the type annotation as a comment.


type_comment is an optional string with the type annotation as a comment.


A single context manager in a with block. context_expr is the context manager, often a Call node. optional_vars is a Name, Tuple or List for the as foo part, or None if that isn’t used.


A yield or yield from expression. Because these are expressions, they must be wrapped in a Expr node if the value sent back is not used.


Source code: Lib/asynchat.py
Deprecated since version 3.6: Please use asyncio instead.
Note
This module exists for backwards compatibility only. For new code we recommend using asyncio.
This module builds on the asyncore infrastructure, simplifying asynchronous clients and servers and making it easier to handle protocols whose elements are terminated by arbitrary strings, or are of variable length. asynchat defines the abstract class async_chat that you subclass, providing implementations of the collect_incoming_data() and found_terminator() methods. It uses the same asynchronous loop as asyncore, and the two types of channel, asyncore.dispatcher and asynchat.async_chat, can freely be mixed in the channel map. Typically an asyncore.dispatcher server channel generates new asynchat.async_chat channel objects as it receives incoming connection requests.
This class is an abstract subclass of asyncore.dispatcher. To make practical use of the code you must subclass async_chat, providing meaningful collect_incoming_data() and found_terminator() methods. The asyncore.dispatcher methods can be used, although not all make sense in a message/response context.
Like asyncore.dispatcher, async_chat defines a set of events that are generated by an analysis of socket conditions after a select() call. Once the polling loop has been started the async_chat object’s methods are called by the event-processing framework with no action on the part of the programmer.
Two class attributes can be modified, to improve performance, or possibly even to conserve memory.
The asynchronous input buffer size (default 4096).
The asynchronous output buffer size (default 4096).
Unlike asyncore.dispatcher, async_chat allows you to define a FIFO queue of producers. A producer need have only one method, more(), which should return data to be transmitted on the channel. The producer indicates exhaustion (i.e. that it contains no more data) by having its more() method return the empty bytes object. At this point the async_chat object removes the producer from the queue and starts using the next producer, if any. When the producer queue is empty the handle_write() method does nothing. You use the channel object’s set_terminator() method to describe how to recognize the end of, or an important breakpoint in, an incoming transmission from the remote endpoint.
To build a functioning async_chat subclass your input methods collect_incoming_data() and found_terminator() must handle the data that the channel receives asynchronously. The methods are described below.
Pushes a None on to the producer queue. When this producer is popped off the queue it causes the channel to be closed.
Called with data holding an arbitrary amount of received data. The default method, which must be overridden, raises a NotImplementedError exception.
In emergencies this method will discard any data held in the input and/or output buffers and the producer queue.
Called when the incoming data stream matches the termination condition set by set_terminator(). The default method, which must be overridden, raises a NotImplementedError exception. The buffered input data should be available via an instance attribute.
Returns the current terminator for the channel.
Pushes data on to the channel’s queue to ensure its transmission. This is all you need to do to have the channel write the data out to the network, although it is possible to use your own producers in more complex schemes to implement encryption and chunking, for example.
Takes a producer object and adds it to the producer queue associated with the channel. When all currently-pushed producers have been exhausted the channel will consume this producer’s data by calling its more() method and send the data to the remote endpoint.
Sets the terminating condition to be recognized on the channel. term may be any of three types of value, corresponding to three different ways to handle incoming protocol data.
term
Description
string
Will call found_terminator() when the string is found in the input stream
integer
Will call found_terminator() when the indicated number of characters have been received
None
The channel continues to collect data forever
Note that any data following the terminator will be available for reading by the channel after found_terminator() is called.
The following partial example shows how HTTP requests can be read with async_chat. A web server might create an http_request_handler object for each incoming client connection. Notice that initially the channel terminator is set to match the blank line at the end of the HTTP headers, and a flag indicates that the headers are being read.
Once the headers have been read, if the request is of type POST (indicating that further data are present in the input stream) then the Content-Length: header is used to set a numeric terminator to read the right amount of data from the channel.
The handle_request() method is called once all relevant input has been marshalled, after setting the channel terminator to None to ensure that any extraneous data sent by the web client are ignored.


This class is an abstract subclass of asyncore.dispatcher. To make practical use of the code you must subclass async_chat, providing meaningful collect_incoming_data() and found_terminator() methods. The asyncore.dispatcher methods can be used, although not all make sense in a message/response context.
Like asyncore.dispatcher, async_chat defines a set of events that are generated by an analysis of socket conditions after a select() call. Once the polling loop has been started the async_chat object’s methods are called by the event-processing framework with no action on the part of the programmer.
Two class attributes can be modified, to improve performance, or possibly even to conserve memory.
The asynchronous input buffer size (default 4096).
The asynchronous output buffer size (default 4096).
Unlike asyncore.dispatcher, async_chat allows you to define a FIFO queue of producers. A producer need have only one method, more(), which should return data to be transmitted on the channel. The producer indicates exhaustion (i.e. that it contains no more data) by having its more() method return the empty bytes object. At this point the async_chat object removes the producer from the queue and starts using the next producer, if any. When the producer queue is empty the handle_write() method does nothing. You use the channel object’s set_terminator() method to describe how to recognize the end of, or an important breakpoint in, an incoming transmission from the remote endpoint.
To build a functioning async_chat subclass your input methods collect_incoming_data() and found_terminator() must handle the data that the channel receives asynchronously. The methods are described below.


The asynchronous input buffer size (default 4096).


The asynchronous output buffer size (default 4096).


Pushes a None on to the producer queue. When this producer is popped off the queue it causes the channel to be closed.


Called with data holding an arbitrary amount of received data. The default method, which must be overridden, raises a NotImplementedError exception.


In emergencies this method will discard any data held in the input and/or output buffers and the producer queue.


Called when the incoming data stream matches the termination condition set by set_terminator(). The default method, which must be overridden, raises a NotImplementedError exception. The buffered input data should be available via an instance attribute.


Returns the current terminator for the channel.


Pushes data on to the channel’s queue to ensure its transmission. This is all you need to do to have the channel write the data out to the network, although it is possible to use your own producers in more complex schemes to implement encryption and chunking, for example.


Takes a producer object and adds it to the producer queue associated with the channel. When all currently-pushed producers have been exhausted the channel will consume this producer’s data by calling its more() method and send the data to the remote endpoint.


Sets the terminating condition to be recognized on the channel. term may be any of three types of value, corresponding to three different ways to handle incoming protocol data.
term
Description
string
Will call found_terminator() when the string is found in the input stream
integer
Will call found_terminator() when the indicated number of characters have been received
None
The channel continues to collect data forever
Note that any data following the terminator will be available for reading by the channel after found_terminator() is called.


Hello World!
asyncio is a library to write concurrent code using the async/await syntax.
asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web-servers, database connection libraries, distributed task queues, etc.
asyncio is often a perfect fit for IO-bound and high-level structured network code.
asyncio provides a set of high-level APIs to:
Additionally, there are low-level APIs for library and framework developers to:
High-level APIs
Low-level APIs
Guides and Tutorials
Note
The source code for asyncio can be found in Lib/asyncio/.


Register a new child handler.
Arrange for callback(pid, returncode, *args) to be called when a process with PID equal to pid terminates. Specifying another callback for the same process replaces the previous handler.
The callback callable must be thread-safe.
Removes the handler for process with PID equal to pid.
The function returns True if the handler was successfully removed, False if there was nothing to remove.
Attach the watcher to an event loop.
If the watcher was previously attached to an event loop, then it is first detached before attaching to the new loop.
Note: loop may be None.
Return True if the watcher is ready to use.
Spawning a subprocess with inactive current child watcher raises RuntimeError.
New in version 3.8.
Close the watcher.
This method has to be called to ensure that underlying resources are cleaned-up.


Register a new child handler.
Arrange for callback(pid, returncode, *args) to be called when a process with PID equal to pid terminates. Specifying another callback for the same process replaces the previous handler.
The callback callable must be thread-safe.


Attach the watcher to an event loop.
If the watcher was previously attached to an event loop, then it is first detached before attaching to the new loop.
Note: loop may be None.


Close the watcher.
This method has to be called to ensure that underlying resources are cleaned-up.


Return True if the watcher is ready to use.
Spawning a subprocess with inactive current child watcher raises RuntimeError.
New in version 3.8.


Removes the handler for process with PID equal to pid.
The function returns True if the handler was successfully removed, False if there was nothing to remove.


Abstract base class for asyncio-compliant event loops.
The Event Loop Methods section lists all methods that an alternative implementation of AbstractEventLoop should have defined.


An abstract base class for asyncio policies.
Get the event loop for the current context.
Return an event loop object implementing the AbstractEventLoop interface.
This method should never return None.
Changed in version 3.6.
Set the event loop for the current context to loop.
Create and return a new event loop object.
This method should never return None.
Get a child process watcher object.
Return a watcher object implementing the AbstractChildWatcher interface.
This function is Unix specific.
Set the current child process watcher to watcher.
This function is Unix specific.


Get a child process watcher object.
Return a watcher object implementing the AbstractChildWatcher interface.
This function is Unix specific.


Get the event loop for the current context.
Return an event loop object implementing the AbstractEventLoop interface.
This method should never return None.
Changed in version 3.6.


Create and return a new event loop object.
This method should never return None.


Set the current child process watcher to watcher.
This function is Unix specific.


Set the event loop for the current context to loop.


Return a set of not yet finished Task objects run by the loop.
If loop is None, get_running_loop() is used for getting current loop.
New in version 3.7.


Special value that can be used as the stdin, stdout or stderr argument to process creation functions. It indicates that the special file os.devnull will be used for the corresponding subprocess stream.


Can be passed to the stdin, stdout or stderr parameters.
If PIPE is passed to stdin argument, the Process.stdin attribute will point to a StreamWriter instance.
If PIPE is passed to stdout or stderr arguments, the Process.stdout and Process.stderr attributes will point to StreamReader instances.


An object that wraps OS processes created by the create_subprocess_exec() and create_subprocess_shell() functions.
This class is designed to have a similar API to the subprocess.Popen class, but there are some notable differences:
This class is not thread safe.
See also the Subprocess and Threads section.
Wait for the child process to terminate.
Set and return the returncode attribute.
Note
This method can deadlock when using stdout=PIPE or stderr=PIPE and the child process generates so much output that it blocks waiting for the OS pipe buffer to accept more data. Use the communicate() method when using pipes to avoid this condition.
Interact with process:
The optional input argument is the data (bytes object) that will be sent to the child process.
Return a tuple (stdout_data, stderr_data).
If either BrokenPipeError or ConnectionResetError exception is raised when writing input into stdin, the exception is ignored. This condition occurs when the process exits before all data are written into stdin.
If it is desired to send data to the process’ stdin, the process needs to be created with stdin=PIPE. Similarly, to get anything other than None in the result tuple, the process has to be created with stdout=PIPE and/or stderr=PIPE arguments.
Note, that the data read is buffered in memory, so do not use this method if the data size is large or unlimited.
Sends the signal signal to the child process.
Note
On Windows, SIGTERM is an alias for terminate(). CTRL_C_EVENT and CTRL_BREAK_EVENT can be sent to processes started with a creationflags parameter which includes CREATE_NEW_PROCESS_GROUP.
Stop the child process.
On POSIX systems this method sends signal.SIGTERM to the child process.
On Windows the Win32 API function TerminateProcess() is called to stop the child process.
Kill the child process.
On POSIX systems this method sends SIGKILL to the child process.
On Windows this method is an alias for terminate().
Standard input stream (StreamWriter) or None if the process was created with stdin=None.
Standard output stream (StreamReader) or None if the process was created with stdout=None.
Standard error stream (StreamReader) or None if the process was created with stderr=None.
Warning
Use the communicate() method rather than process.stdin.write(), await process.stdout.read() or await process.stderr.read. This avoids deadlocks due to streams pausing reading or writing and blocking the child process.
Process identification number (PID).
Note that for processes created by the create_subprocess_shell() function, this attribute is the PID of the spawned shell.
Return code of the process when it exits.
A None value indicates that the process has not terminated yet.
A negative value -N indicates that the child was terminated by signal N (POSIX only).


Interact with process:
The optional input argument is the data (bytes object) that will be sent to the child process.
Return a tuple (stdout_data, stderr_data).
If either BrokenPipeError or ConnectionResetError exception is raised when writing input into stdin, the exception is ignored. This condition occurs when the process exits before all data are written into stdin.
If it is desired to send data to the process’ stdin, the process needs to be created with stdin=PIPE. Similarly, to get anything other than None in the result tuple, the process has to be created with stdout=PIPE and/or stderr=PIPE arguments.
Note, that the data read is buffered in memory, so do not use this method if the data size is large or unlimited.


Kill the child process.
On POSIX systems this method sends SIGKILL to the child process.
On Windows this method is an alias for terminate().


Process identification number (PID).
Note that for processes created by the create_subprocess_shell() function, this attribute is the PID of the spawned shell.


Return code of the process when it exits.
A None value indicates that the process has not terminated yet.
A negative value -N indicates that the child was terminated by signal N (POSIX only).


Sends the signal signal to the child process.
Note
On Windows, SIGTERM is an alias for terminate(). CTRL_C_EVENT and CTRL_BREAK_EVENT can be sent to processes started with a creationflags parameter which includes CREATE_NEW_PROCESS_GROUP.


Standard error stream (StreamReader) or None if the process was created with stderr=None.


Standard input stream (StreamWriter) or None if the process was created with stdin=None.


Standard output stream (StreamReader) or None if the process was created with stdout=None.


Stop the child process.
On POSIX systems this method sends signal.SIGTERM to the child process.
On Windows the Win32 API function TerminateProcess() is called to stop the child process.


Wait for the child process to terminate.
Set and return the returncode attribute.
Note
This method can deadlock when using stdout=PIPE or stderr=PIPE and the child process generates so much output that it blocks waiting for the OS pipe buffer to accept more data. Use the communicate() method when using pipes to avoid this condition.


Special value that can be used as the stderr argument and indicates that standard error should be redirected into standard output.


Run awaitable objects in the aws iterable concurrently. Return an iterator of coroutines. Each coroutine returned can be awaited to get the earliest next result from the iterable of the remaining awaitables.
Raises asyncio.TimeoutError if the timeout occurs before all Futures are done.
Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.
Example:


Base protocol with methods that all protocols share.


Called when the connection is lost or closed.
The argument is either an exception object or None. The latter means a regular EOF is received, or the connection was aborted or closed by this side of the connection.


Called when a connection is made.
The transport argument is the transport representing the connection. The protocol is responsible for storing the reference to its transport.


Called when the transport’s buffer goes over the high watermark.


Called when the transport’s buffer drains below the low watermark.


Base class for all transports. Contains methods that all asyncio transports share.


Close the transport.
If the transport has a buffer for outgoing data, buffered data will be flushed asynchronously. No more data will be received. After all buffered data is flushed, the protocol’s protocol.connection_lost() method will be called with None as its argument.


Return information about the transport or underlying resources it uses.
name is a string representing the piece of transport-specific information to get.
default is the value to return if the information is not available, or if the transport does not support querying it with the given third-party event loop implementation or on the current platform.
For example, the following code attempts to get the underlying socket object of the transport:
Categories of information that can be queried on some transports:
socket:
SSL socket:
pipe:
subprocess:


Return True if the transport is closing or is closed.


Set a new protocol.
Switching protocol should only be done when both protocols are documented to support the switch.


A bounded semaphore object. Not thread-safe.
Bounded Semaphore is a version of Semaphore that raises a ValueError in release() if it increases the internal counter above the initial value.
Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.


A base class for implementing streaming protocols with manual control of the receive buffer.


Called when the buffer was updated with the received data.
nbytes is the total number of bytes that were written to the buffer.


See the documentation of the protocol.eof_received() method.


Called to allocate a new receive buffer.
sizehint is the recommended minimum size for the returned buffer. It is acceptable to return smaller or larger buffers than what sizehint suggests. When set to -1, the buffer size can be arbitrary. It is an error to return a buffer with a zero size.
get_buffer() must return an object implementing the buffer protocol.


The operation has been cancelled.
This exception can be caught to perform custom operations when asyncio Tasks are cancelled. In almost all situations the exception must be re-raised.
Changed in version 3.8: CancelledError is now a subclass of BaseException.


A Condition object. Not thread-safe.
An asyncio condition primitive can be used by a task to wait for some event to happen and then get exclusive access to a shared resource.
In essence, a Condition object combines the functionality of an Event and a Lock. It is possible to have multiple Condition objects share one Lock, which allows coordinating exclusive access to a shared resource between different tasks interested in particular states of that shared resource.
The optional lock argument must be a Lock object or None. In the latter case a new Lock object is created automatically.
Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.
The preferred way to use a Condition is an async with statement:
which is equivalent to:
Acquire the underlying lock.
This method waits until the underlying lock is unlocked, sets it to locked and returns True.
Wake up at most n tasks (1 by default) waiting on this condition. The method is no-op if no tasks are waiting.
The lock must be acquired before this method is called and released shortly after. If called with an unlocked lock a RuntimeError error is raised.
Return True if the underlying lock is acquired.
Wake up all tasks waiting on this condition.
This method acts like notify(), but wakes up all waiting tasks.
The lock must be acquired before this method is called and released shortly after. If called with an unlocked lock a RuntimeError error is raised.
Release the underlying lock.
When invoked on an unlocked lock, a RuntimeError is raised.
Wait until notified.
If the calling task has not acquired the lock when this method is called, a RuntimeError is raised.
This method releases the underlying lock, and then blocks until it is awakened by a notify() or notify_all() call. Once awakened, the Condition re-acquires its lock and this method returns True.
Wait until a predicate becomes true.
The predicate must be a callable which result will be interpreted as a boolean value. The final value is the return value.


Acquire the underlying lock.
This method waits until the underlying lock is unlocked, sets it to locked and returns True.


Return True if the underlying lock is acquired.


Wake up at most n tasks (1 by default) waiting on this condition. The method is no-op if no tasks are waiting.
The lock must be acquired before this method is called and released shortly after. If called with an unlocked lock a RuntimeError error is raised.


Wake up all tasks waiting on this condition.
This method acts like notify(), but wakes up all waiting tasks.
The lock must be acquired before this method is called and released shortly after. If called with an unlocked lock a RuntimeError error is raised.


Release the underlying lock.
When invoked on an unlocked lock, a RuntimeError is raised.


Wait until notified.
If the calling task has not acquired the lock when this method is called, a RuntimeError is raised.
This method releases the underlying lock, and then blocks until it is awakened by a notify() or notify_all() call. Once awakened, the Condition re-acquires its lock and this method returns True.


Wait until a predicate becomes true.
The predicate must be a callable which result will be interpreted as a boolean value. The final value is the return value.


Decorator to mark generator-based coroutines.
This decorator enables legacy generator-based coroutines to be compatible with async/await code:
This decorator should not be used for async def coroutines.
Deprecated since version 3.8, will be removed in version 3.10: Use async def instead.


Create a subprocess.
The limit argument sets the buffer limit for StreamReader wrappers for Process.stdout and Process.stderr (if subprocess.PIPE is passed to stdout and stderr arguments).
Return a Process instance.
See the documentation of loop.subprocess_exec() for other parameters.
Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.


Run the cmd shell command.
The limit argument sets the buffer limit for StreamReader wrappers for Process.stdout and Process.stderr (if subprocess.PIPE is passed to stdout and stderr arguments).
Return a Process instance.
See the documentation of loop.subprocess_shell() for other parameters.
Important
It is the application’s responsibility to ensure that all whitespace and special characters are quoted appropriately to avoid shell injection vulnerabilities. The shlex.quote() function can be used to properly escape whitespace and special shell characters in strings that are going to be used to construct shell commands.
Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.


Wrap the coro coroutine into a Task and schedule its execution. Return the Task object.
If name is not None, it is set as the name of the task using Task.set_name().
The task is executed in the loop returned by get_running_loop(), RuntimeError is raised if there is no running loop in current thread.
This function has been added in Python 3.7. Prior to Python 3.7, the low-level asyncio.ensure_future() function can be used instead:
New in version 3.7.
Changed in version 3.8: Added the name parameter.


Return the currently running Task instance, or None if no task is running.
If loop is None get_running_loop() is used to get the current loop.
New in version 3.7.


The base class for implementing datagram (UDP) protocols.


Called when a datagram is received. data is a bytes object containing the incoming data. addr is the address of the peer sending the data; the exact format depends on the transport.


Called when a previous send or receive operation raises an OSError. exc is the OSError instance.
This method is called in rare conditions, when the transport (e.g. UDP) detects that a datagram could not be delivered to its recipient. In many conditions though, undeliverable datagrams will be silently dropped.


A transport for datagram (UDP) connections.
Instances of the DatagramTransport class are returned from the loop.create_datagram_endpoint() event loop method.


Close the transport immediately, without waiting for pending operations to complete. Buffered data will be lost. No more data will be received. The protocol’s protocol.connection_lost() method will eventually be called with None as its argument.


Send the data bytes to the remote peer given by addr (a transport-dependent target address). If addr is None, the data is sent to the target address given on transport creation.
This method does not block; it buffers the data and arranges for it to be sent out asynchronously.


The default asyncio policy. Uses SelectorEventLoop on Unix and ProactorEventLoop on Windows.
There is no need to install the default policy manually. asyncio is configured to use the default policy automatically.
Changed in version 3.8: On Windows, ProactorEventLoop is now used by default.


Return:
If obj is neither of the above a TypeError is raised.
Important
See also the create_task() function which is the preferred way for creating new Tasks.
Changed in version 3.5.1: The function accepts any awaitable object.


An event object. Not thread-safe.
An asyncio event can be used to notify multiple asyncio tasks that some event has happened.
An Event object manages an internal flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is set to true. The flag is set to false initially.
Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.
Example:
Wait until the event is set.
If the event is set, return True immediately. Otherwise block until another task calls set().
Set the event.
All tasks waiting for event to be set will be immediately awakened.
Clear (unset) the event.
Tasks awaiting on wait() will now block until the set() method is called again.
Return True if the event is set.


Clear (unset) the event.
Tasks awaiting on wait() will now block until the set() method is called again.


Set the event.
All tasks waiting for event to be set will be immediately awakened.


Wait until the event is set.
If the event is set, return True immediately. Otherwise block until another task calls set().


This implementation reaps every terminated processes by calling os.waitpid(-1) directly, possibly breaking other code spawning processes and waiting for their termination.
There is no noticeable overhead when handling a big number of children (O(1) each time a child terminates).
This solution requires a running event loop in the main thread to work, as SafeChildWatcher.


A Future represents an eventual result of an asynchronous operation. Not thread-safe.
Future is an awaitable object. Coroutines can await on Future objects until they either have a result or an exception set, or until they are cancelled.
Typically Futures are used to enable low-level callback-based code (e.g. in protocols implemented using asyncio transports) to interoperate with high-level async/await code.
The rule of thumb is to never expose Future objects in user-facing APIs, and the recommended way to create a Future object is to call loop.create_future(). This way alternative event loop implementations can inject their own optimized implementations of a Future object.
Changed in version 3.7: Added support for the contextvars module.
Return the result of the Future.
If the Future is done and has a result set by the set_result() method, the result value is returned.
If the Future is done and has an exception set by the set_exception() method, this method raises the exception.
If the Future has been cancelled, this method raises a CancelledError exception.
If the Future’s result isn’t yet available, this method raises a InvalidStateError exception.
Mark the Future as done and set its result.
Raises a InvalidStateError error if the Future is already done.
Mark the Future as done and set an exception.
Raises a InvalidStateError error if the Future is already done.
Return True if the Future is done.
A Future is done if it was cancelled or if it has a result or an exception set with set_result() or set_exception() calls.
Return True if the Future was cancelled.
The method is usually used to check if a Future is not cancelled before setting a result or an exception for it:
Add a callback to be run when the Future is done.
The callback is called with the Future object as its only argument.
If the Future is already done when this method is called, the callback is scheduled with loop.call_soon().
An optional keyword-only context argument allows specifying a custom contextvars.Context for the callback to run in. The current context is used when no context is provided.
functools.partial() can be used to pass parameters to the callback, e.g.:
Changed in version 3.7: The context keyword-only parameter was added. See PEP 567 for more details.
Remove callback from the callbacks list.
Returns the number of callbacks removed, which is typically 1, unless a callback was added more than once.
Cancel the Future and schedule callbacks.
If the Future is already done or cancelled, return False. Otherwise, change the Future’s state to cancelled, schedule the callbacks, and return True.
Changed in version 3.9: Added the msg parameter.
Return the exception that was set on this Future.
The exception (or None if no exception was set) is returned only if the Future is done.
If the Future has been cancelled, this method raises a CancelledError exception.
If the Future isn’t done yet, this method raises an InvalidStateError exception.
Return the event loop the Future object is bound to.
New in version 3.7.


Add a callback to be run when the Future is done.
The callback is called with the Future object as its only argument.
If the Future is already done when this method is called, the callback is scheduled with loop.call_soon().
An optional keyword-only context argument allows specifying a custom contextvars.Context for the callback to run in. The current context is used when no context is provided.
functools.partial() can be used to pass parameters to the callback, e.g.:
Changed in version 3.7: The context keyword-only parameter was added. See PEP 567 for more details.


Cancel the Future and schedule callbacks.
If the Future is already done or cancelled, return False. Otherwise, change the Future’s state to cancelled, schedule the callbacks, and return True.
Changed in version 3.9: Added the msg parameter.


Return True if the Future was cancelled.
The method is usually used to check if a Future is not cancelled before setting a result or an exception for it:


Return True if the Future is done.
A Future is done if it was cancelled or if it has a result or an exception set with set_result() or set_exception() calls.


Return the exception that was set on this Future.
The exception (or None if no exception was set) is returned only if the Future is done.
If the Future has been cancelled, this method raises a CancelledError exception.
If the Future isn’t done yet, this method raises an InvalidStateError exception.


Return the event loop the Future object is bound to.
New in version 3.7.


Remove callback from the callbacks list.
Returns the number of callbacks removed, which is typically 1, unless a callback was added more than once.


Return the result of the Future.
If the Future is done and has a result set by the set_result() method, the result value is returned.
If the Future is done and has an exception set by the set_exception() method, this method raises the exception.
If the Future has been cancelled, this method raises a CancelledError exception.
If the Future’s result isn’t yet available, this method raises a InvalidStateError exception.


Mark the Future as done and set an exception.
Raises a InvalidStateError error if the Future is already done.


Mark the Future as done and set its result.
Raises a InvalidStateError error if the Future is already done.


Run awaitable objects in the aws sequence concurrently.
If any awaitable in aws is a coroutine, it is automatically scheduled as a Task.
If all awaitables are completed successfully, the result is an aggregate list of returned values. The order of result values corresponds to the order of awaitables in aws.
If return_exceptions is False (default), the first raised exception is immediately propagated to the task that awaits on gather(). Other awaitables in the aws sequence won’t be cancelled and will continue to run.
If return_exceptions is True, exceptions are treated the same as successful results, and aggregated in the result list.
If gather() is cancelled, all submitted awaitables (that have not completed yet) are also cancelled.
If any Task or Future from the aws sequence is cancelled, it is treated as if it raised CancelledError – the gather() call is not cancelled in this case. This is to prevent the cancellation of one submitted Task/Future to cause other Tasks/Futures to be cancelled.
Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.
Example:
Note
If return_exceptions is False, cancelling gather() after it has been marked done won’t cancel any submitted awaitables. For instance, gather can be marked done after propagating an exception to the caller, therefore, calling gather.cancel() after catching an exception (raised by one of the awaitables) from gather won’t cancel any other awaitables.
Changed in version 3.7: If the gather itself is cancelled, the cancellation is propagated regardless of return_exceptions.


Return the current child watcher for the current policy.


Get the current event loop.
If there is no current event loop set in the current OS thread, the OS thread is main, and set_event_loop() has not yet been called, asyncio will create a new event loop and set it as the current one.
Because this function has rather complex behavior (especially when custom event loop policies are in use), using the get_running_loop() function is preferred to get_event_loop() in coroutines and callbacks.
Consider also using the asyncio.run() function instead of using lower level functions to manually create and close an event loop.


Return the running event loop in the current OS thread.
If there is no running event loop a RuntimeError is raised. This function can only be called from a coroutine or a callback.
New in version 3.7.


A callback wrapper object returned by loop.call_soon(), loop.call_soon_threadsafe().
Cancel the callback. If the callback has already been canceled or executed, this method has no effect.
Return True if the callback was cancelled.
New in version 3.7.


Cancel the callback. If the callback has already been canceled or executed, this method has no effect.


Return True if the callback was cancelled.
New in version 3.7.


The requested read operation did not complete fully.
Raised by the asyncio stream APIs.
This exception is a subclass of EOFError.
The total number (int) of expected bytes.
A string of bytes read before the end of stream was reached.


The total number (int) of expected bytes.


A string of bytes read before the end of stream was reached.


Invalid internal state of Task or Future.
Can be raised in situations like setting a result value for a Future object that already has a result value set.


Return True if obj is a coroutine object.
This method is different from inspect.iscoroutine() because it returns True for generator-based coroutines.


Return True if func is a coroutine function.
This method is different from inspect.iscoroutinefunction() because it returns True for generator-based coroutine functions decorated with @coroutine.


Return True if obj is either of:
New in version 3.5.


A variant of Queue that retrieves most recently added entries first (last in, first out).


Reached the buffer size limit while looking for a separator.
Raised by the asyncio stream APIs.
The total number of to be consumed bytes.


The total number of to be consumed bytes.


Implements a mutex lock for asyncio tasks. Not thread-safe.
An asyncio lock can be used to guarantee exclusive access to a shared resource.
The preferred way to use a Lock is an async with statement:
which is equivalent to:
Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.
Acquire the lock.
This method waits until the lock is unlocked, sets it to locked and returns True.
When more than one coroutine is blocked in acquire() waiting for the lock to be unlocked, only one coroutine eventually proceeds.
Acquiring a lock is fair: the coroutine that proceeds will be the first coroutine that started waiting on the lock.
Release the lock.
When the lock is locked, reset it to unlocked and return.
If the lock is unlocked, a RuntimeError is raised.
Return True if the lock is locked.


Acquire the lock.
This method waits until the lock is unlocked, sets it to locked and returns True.
When more than one coroutine is blocked in acquire() waiting for the lock to be unlocked, only one coroutine eventually proceeds.
Acquiring a lock is fair: the coroutine that proceeds will be the first coroutine that started waiting on the lock.


Release the lock.
When the lock is locked, reset it to unlocked and return.
If the lock is unlocked, a RuntimeError is raised.


Start monitoring the fd file descriptor for read availability and invoke callback with the specified arguments once fd is available for reading.


Set callback as the handler for the signum signal.
The callback will be invoked by loop, along with other queued callbacks and runnable coroutines of that event loop. Unlike signal handlers registered using signal.signal(), a callback registered with this function is allowed to interact with the event loop.
Raise ValueError if the signal number is invalid or uncatchable. Raise RuntimeError if there is a problem setting up the handler.
Use functools.partial() to pass keyword arguments to callback.
Like signal.signal(), this function must be invoked in the main thread.


Start monitoring the fd file descriptor for write availability and invoke callback with the specified arguments once fd is available for writing.
Use functools.partial() to pass keyword arguments to callback.


Schedule callback to be called at the given absolute timestamp when (an int or a float), using the same time reference as loop.time().
This method’s behavior is the same as call_later().
An instance of asyncio.TimerHandle is returned which can be used to cancel the callback.
Changed in version 3.7: The context keyword-only parameter was added. See PEP 567 for more details.
Changed in version 3.8: In Python 3.7 and earlier with the default event loop implementation, the difference between when and the current time could not exceed one day. This has been fixed in Python 3.8.


Call the current event loop exception handler.
context is a dict object containing the following keys (new keys may be introduced in future Python versions):
Note
This method should not be overloaded in subclassed event loops. For custom exception handling, use the set_exception_handler() method.


Schedule callback to be called after the given delay number of seconds (can be either an int or a float).
An instance of asyncio.TimerHandle is returned which can be used to cancel the callback.
callback will be called exactly once. If two callbacks are scheduled for exactly the same time, the order in which they are called is undefined.
The optional positional args will be passed to the callback when it is called. If you want the callback to be called with keyword arguments use functools.partial().
An optional keyword-only context argument allows specifying a custom contextvars.Context for the callback to run in. The current context is used when no context is provided.
Changed in version 3.7: The context keyword-only parameter was added. See PEP 567 for more details.
Changed in version 3.8: In Python 3.7 and earlier with the default event loop implementation, the delay could not exceed one day. This has been fixed in Python 3.8.


Schedule the callback callback to be called with args arguments at the next iteration of the event loop.
Callbacks are called in the order in which they are registered. Each callback will be called exactly once.
An optional keyword-only context argument allows specifying a custom contextvars.Context for the callback to run in. The current context is used when no context is provided.
An instance of asyncio.Handle is returned, which can be used later to cancel the callback.
This method is not thread-safe.


A thread-safe variant of call_soon(). Must be used to schedule callbacks from another thread.
See the concurrency and multithreading section of the documentation.


Close the event loop.
The loop must not be running when this function is called. Any pending callbacks will be discarded.
This method clears all queues and shuts down the executor, but does not wait for the executor to finish.
This method is idempotent and irreversible. No other methods should be called after the event loop is closed.


Wrap an already accepted connection into a transport/protocol pair.
This method can be used by servers that accept connections outside of asyncio but that use asyncio to handle them.
Parameters:
Returns a (transport, protocol) pair.
New in version 3.7: The ssl_handshake_timeout parameter.
New in version 3.5.3.


Register the read end of pipe in the event loop.
protocol_factory must be a callable returning an asyncio protocol implementation.
pipe is a file-like object.
Return pair (transport, protocol), where transport supports the ReadTransport interface and protocol is an object instantiated by the protocol_factory.
With SelectorEventLoop event loop, the pipe is set to non-blocking mode.


Register the write end of pipe in the event loop.
protocol_factory must be a callable returning an asyncio protocol implementation.
pipe is file-like object.
Return pair (transport, protocol), where transport supports WriteTransport interface and protocol is an object instantiated by the protocol_factory.
With SelectorEventLoop event loop, the pipe is set to non-blocking mode.


Open a streaming transport connection to a given address specified by host and port.
The socket family can be either AF_INET or AF_INET6 depending on host (or the family argument, if provided).
The socket type will be SOCK_STREAM.
protocol_factory must be a callable returning an asyncio protocol implementation.
This method will try to establish the connection in the background. When successful, it returns a (transport, protocol) pair.
The chronological synopsis of the underlying operation is as follows:
The created transport is an implementation-dependent bidirectional stream.
Other arguments:
ssl: if given and not false, a SSL/TLS transport is created (by default a plain TCP transport is created). If ssl is a ssl.SSLContext object, this context is used to create the transport; if ssl is True, a default context returned from ssl.create_default_context() is used.
See also
SSL/TLS security considerations
New in version 3.8: Added the happy_eyeballs_delay and interleave parameters.
Happy Eyeballs Algorithm: Success with Dual-Stack Hosts. When a server’s IPv4 path and protocol are working, but the server’s IPv6 path and protocol are not working, a dual-stack client application experiences significant connection delay compared to an IPv4-only client. This is undesirable because it causes the dual- stack client to have a worse user experience. This document specifies requirements for algorithms that reduce this user-visible delay and provides an algorithm.
For more information: https://tools.ietf.org/html/rfc6555
New in version 3.7: The ssl_handshake_timeout parameter.
Changed in version 3.6: The socket option TCP_NODELAY is set by default for all TCP connections.
Changed in version 3.5: Added support for SSL/TLS in ProactorEventLoop.
See also
The open_connection() function is a high-level alternative API. It returns a pair of (StreamReader, StreamWriter) that can be used directly in async/await code.


Note
The parameter reuse_address is no longer supported, as using SO_REUSEADDR poses a significant security concern for UDP. Explicitly passing reuse_address=True will raise an exception.
When multiple processes with differing UIDs assign sockets to an identical UDP socket address with SO_REUSEADDR, incoming packets can become randomly distributed among the sockets.
For supported platforms, reuse_port can be used as a replacement for similar functionality. With reuse_port, SO_REUSEPORT is used instead, which specifically prevents processes with differing UIDs from assigning sockets to the same socket address.
Create a datagram connection.
The socket family can be either AF_INET, AF_INET6, or AF_UNIX, depending on host (or the family argument, if provided).
The socket type will be SOCK_DGRAM.
protocol_factory must be a callable returning a protocol implementation.
A tuple of (transport, protocol) is returned on success.
Other arguments:
See UDP echo client protocol and UDP echo server protocol examples.
Changed in version 3.4.4: The family, proto, flags, reuse_address, reuse_port, *allow_broadcast, and sock parameters were added.
Changed in version 3.8.1: The reuse_address parameter is no longer supported due to security concerns.
Changed in version 3.8: Added support for Windows.


Create an asyncio.Future object attached to the event loop.
This is the preferred way to create Futures in asyncio. This lets third-party event loops provide alternative implementations of the Future object (with better performance or instrumentation).
New in version 3.5.2.


Create a TCP server (socket type SOCK_STREAM) listening on port of the host address.
Returns a Server object.
Arguments:
The host parameter can be set to several types which determine where the server would be listening:
New in version 3.7: Added ssl_handshake_timeout and start_serving parameters.
Changed in version 3.6: The socket option TCP_NODELAY is set by default for all TCP connections.
Changed in version 3.5: Added support for SSL/TLS in ProactorEventLoop.
Changed in version 3.5.1: The host parameter can be a sequence of strings.
See also
The start_server() function is a higher-level alternative API that returns a pair of StreamReader and StreamWriter that can be used in an async/await code.


Schedule the execution of a Coroutines. Return a Task object.
Third-party event loops can use their own subclass of Task for interoperability. In this case, the result type is a subclass of Task.
If the name argument is provided and not None, it is set as the name of the task using Task.set_name().
Changed in version 3.8: Added the name parameter.


Create a Unix connection.
The socket family will be AF_UNIX; socket type will be SOCK_STREAM.
A tuple of (transport, protocol) is returned on success.
path is the name of a Unix domain socket and is required, unless a sock parameter is specified. Abstract Unix sockets, str, bytes, and Path paths are supported.
See the documentation of the loop.create_connection() method for information about arguments to this method.
Availability: Unix.
New in version 3.7: The ssl_handshake_timeout parameter.
Changed in version 3.7: The path parameter can now be a path-like object.


Similar to loop.create_server() but works with the AF_UNIX socket family.
path is the name of a Unix domain socket, and is required, unless a sock argument is provided. Abstract Unix sockets, str, bytes, and Path paths are supported.
See the documentation of the loop.create_server() method for information about arguments to this method.
Availability: Unix.
New in version 3.7: The ssl_handshake_timeout and start_serving parameters.
Changed in version 3.7: The path parameter can now be a Path object.


Default exception handler.
This is called when an exception occurs and no exception handler is set. This can be called by a custom exception handler that wants to defer to the default handler behavior.
context parameter has the same meaning as in call_exception_handler().


Asynchronous version of socket.getaddrinfo().


Asynchronous version of socket.getnameinfo().


Get the debug mode (bool) of the event loop.
The default value is True if the environment variable PYTHONASYNCIODEBUG is set to a non-empty string, False otherwise.


Return the current exception handler, or None if no custom exception handler was set.
New in version 3.5.2.


Return a task factory or None if the default one is in use.


Return True if the event loop was closed.


Return True if the event loop is currently running.


Stop monitoring the fd file descriptor for read availability.


Remove the handler for the sig signal.
Return True if the signal handler was removed, or False if no handler was set for the given signal.
Availability: Unix.


Stop monitoring the fd file descriptor for write availability.


Run the event loop until stop() is called.
If stop() is called before run_forever() is called, the loop will poll the I/O selector once with a timeout of zero, run all callbacks scheduled in response to I/O events (and those that were already scheduled), and then exit.
If stop() is called while run_forever() is running, the loop will run the current batch of callbacks and then exit. Note that new callbacks scheduled by callbacks will not run in this case; instead, they will run the next time run_forever() or run_until_complete() is called.


Arrange for func to be called in the specified executor.
The executor argument should be an concurrent.futures.Executor instance. The default executor is used if executor is None.
Example:
This method returns a asyncio.Future object.
Use functools.partial() to pass keyword arguments to func.
Changed in version 3.5.3: loop.run_in_executor() no longer configures the max_workers of the thread pool executor it creates, instead leaving it up to the thread pool executor (ThreadPoolExecutor) to set the default.


Run until the future (an instance of Future) has completed.
If the argument is a coroutine object it is implicitly scheduled to run as a asyncio.Task.
Return the Future’s result or raise its exception.


Send a file over a transport. Return the total number of bytes sent.
The method uses high-performance os.sendfile() if available.
file must be a regular file object opened in binary mode.
offset tells from where to start reading the file. If specified, count is the total number of bytes to transmit as opposed to sending the file until EOF is reached. File position is always updated, even when this method raises an error, and file.tell() can be used to obtain the actual number of bytes sent.
fallback set to True makes asyncio to manually read and send the file when the platform does not support the sendfile system call (e.g. Windows or SSL socket on Unix).
Raise SendfileNotAvailableError if the system does not support the sendfile syscall and fallback is False.
New in version 3.7.


Set the debug mode of the event loop.
Changed in version 3.7: The new Python Development Mode can now also be used to enable the debug mode.


Set executor as the default executor used by run_in_executor(). executor should be an instance of ThreadPoolExecutor.
Deprecated since version 3.8: Using an executor that is not an instance of ThreadPoolExecutor is deprecated and will trigger an error in Python 3.9.
executor must be an instance of concurrent.futures.ThreadPoolExecutor.


Set handler as the new event loop exception handler.
If handler is None, the default exception handler will be set. Otherwise, handler must be a callable with the signature matching (loop, context), where loop is a reference to the active event loop, and context is a dict object containing the details of the exception (see call_exception_handler() documentation for details about context).


Set a task factory that will be used by loop.create_task().
If factory is None the default task factory will be set. Otherwise, factory must be a callable with the signature matching (loop, coro), where loop is a reference to the active event loop, and coro is a coroutine object. The callable must return a asyncio.Future-compatible object.


Schedule all currently open asynchronous generator objects to close with an aclose() call. After calling this method, the event loop will issue a warning if a new asynchronous generator is iterated. This should be used to reliably finalize all scheduled asynchronous generators.
Note that there is no need to call this function when asyncio.run() is used.
Example:
New in version 3.6.


Schedule the closure of the default executor and wait for it to join all of the threads in the ThreadPoolExecutor. After calling this method, a RuntimeError will be raised if loop.run_in_executor() is called while using the default executor.
Note that there is no need to call this function when asyncio.run() is used.
New in version 3.9.


Accept a connection. Modeled after the blocking socket.accept() method.
The socket must be bound to an address and listening for connections. The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection.
sock must be a non-blocking socket.
Changed in version 3.7: Even though the method was always documented as a coroutine method, before Python 3.7 it returned a Future. Since Python 3.7, this is an async def method.
See also
loop.create_server() and start_server().


Connect sock to a remote socket at address.
Asynchronous version of socket.connect().
sock must be a non-blocking socket.
Changed in version 3.5.2: address no longer needs to be resolved. sock_connect will try to check if the address is already resolved by calling socket.inet_pton(). If not, loop.getaddrinfo() will be used to resolve the address.
See also
loop.create_connection() and asyncio.open_connection().


Receive up to nbytes from sock. Asynchronous version of socket.recv().
Return the received data as a bytes object.
sock must be a non-blocking socket.
Changed in version 3.7: Even though this method was always documented as a coroutine method, releases before Python 3.7 returned a Future. Since Python 3.7 this is an async def method.


Receive data from sock into the buf buffer. Modeled after the blocking socket.recv_into() method.
Return the number of bytes written to the buffer.
sock must be a non-blocking socket.
New in version 3.7.


Send data to the sock socket. Asynchronous version of socket.sendall().
This method continues to send to the socket until either all data in data has been sent or an error occurs. None is returned on success. On error, an exception is raised. Additionally, there is no way to determine how much data, if any, was successfully processed by the receiving end of the connection.
sock must be a non-blocking socket.
Changed in version 3.7: Even though the method was always documented as a coroutine method, before Python 3.7 it returned an Future. Since Python 3.7, this is an async def method.


Send a file using high-performance os.sendfile if possible. Return the total number of bytes sent.
Asynchronous version of socket.sendfile().
sock must be a non-blocking socket.SOCK_STREAM socket.
file must be a regular file object open in binary mode.
offset tells from where to start reading the file. If specified, count is the total number of bytes to transmit as opposed to sending the file until EOF is reached. File position is always updated, even when this method raises an error, and file.tell() can be used to obtain the actual number of bytes sent.
fallback, when set to True, makes asyncio manually read and send the file when the platform does not support the sendfile syscall (e.g. Windows or SSL socket on Unix).
Raise SendfileNotAvailableError if the system does not support sendfile syscall and fallback is False.
sock must be a non-blocking socket.
New in version 3.7.


Upgrade an existing transport-based connection to TLS.
Return a new transport instance, that the protocol must start using immediately after the await. The transport instance passed to the start_tls method should never be used again.
Parameters:
New in version 3.7.


Create a subprocess from one or more string arguments specified by args.
args must be a list of strings represented by:
The first string specifies the program executable, and the remaining strings specify the arguments. Together, string arguments form the argv of the program.
This is similar to the standard library subprocess.Popen class called with shell=False and the list of strings passed as the first argument; however, where Popen takes a single argument which is list of strings, subprocess_exec takes multiple string arguments.
The protocol_factory must be a callable returning a subclass of the asyncio.SubprocessProtocol class.
Other parameters:
stdin can be any of these:
stdout can be any of these:
stderr can be any of these:
All other keyword arguments are passed to subprocess.Popen without interpretation, except for bufsize, universal_newlines, shell, text, encoding and errors, which should not be specified at all.
The asyncio subprocess API does not support decoding the streams as text. bytes.decode() can be used to convert the bytes returned from the stream to text.
See the constructor of the subprocess.Popen class for documentation on other arguments.
Returns a pair of (transport, protocol), where transport conforms to the asyncio.SubprocessTransport base class and protocol is an object instantiated by the protocol_factory.


Create a subprocess from cmd, which can be a str or a bytes string encoded to the filesystem encoding, using the platform’s “shell” syntax.
This is similar to the standard library subprocess.Popen class called with shell=True.
The protocol_factory must be a callable returning a subclass of the SubprocessProtocol class.
See subprocess_exec() for more details about the remaining arguments.
Returns a pair of (transport, protocol), where transport conforms to the SubprocessTransport base class and protocol is an object instantiated by the protocol_factory.


Return the current time, as a float value, according to the event loop’s internal monotonic clock.


This implementation registers a SIGCHLD signal handler on instantiation. That can break third-party code that installs a custom handler for SIGCHLD signal.
The watcher avoids disrupting other code spawning processes by polling every process explicitly on a SIGCHLD signal.
There is no limitation for running subprocesses from different threads once the watcher is installed.
The solution is safe but it has a significant overhead when handling a big number of processes (O(n) each time a SIGCHLD is received).
New in version 3.8.


Establish a network connection and return a pair of (reader, writer) objects.
The returned reader and writer objects are instances of StreamReader and StreamWriter classes.
The loop argument is optional and can always be determined automatically when this function is awaited from a coroutine.
limit determines the buffer size limit used by the returned StreamReader instance. By default the limit is set to 64 KiB.
The rest of the arguments are passed directly to loop.create_connection().
New in version 3.7: The ssl_handshake_timeout parameter.


Establish a Unix socket connection and return a pair of (reader, writer).
Similar to open_connection() but operates on Unix sockets.
See also the documentation of loop.create_unix_connection().
Availability: Unix.
New in version 3.7: The ssl_handshake_timeout parameter.
Changed in version 3.7: The path parameter can now be a path-like object


This implementation polls process file descriptors (pidfds) to await child process termination. In some respects, PidfdChildWatcher is a “Goldilocks” child watcher implementation. It doesn’t require signals or threads, doesn’t interfere with any processes launched outside the event loop, and scales linearly with the number of subprocesses launched by the event loop. The main disadvantage is that pidfds are specific to Linux, and only work on recent (5.3+) kernels.
New in version 3.9.


A variant of Queue; retrieves entries in priority order (lowest first).
Entries are typically tuples of the form (priority_number, data).


An event loop for Windows that uses “I/O Completion Ports” (IOCP).
Availability: Windows.
See also
MSDN documentation on I/O Completion Ports.


The base class for implementing streaming protocols (TCP, Unix sockets, etc).


Called when some data is received. data is a non-empty bytes object containing the incoming data.
Whether the data is buffered, chunked or reassembled depends on the transport. In general, you shouldn’t rely on specific semantics and instead make your parsing generic and flexible. However, data is always received in the correct order.
The method can be called an arbitrary number of times while a connection is open.
However, protocol.eof_received() is called at most once. Once eof_received() is called, data_received() is not called anymore.


Called when the other end signals it won’t send any more data (for example by calling transport.write_eof(), if the other end also uses asyncio).
This method may return a false value (including None), in which case the transport will close itself. Conversely, if this method returns a true value, the protocol used determines whether to close the transport. Since the default implementation returns None, it implicitly closes the connection.
Some transports, including SSL, don’t support half-closed connections, in which case returning true from this method will result in the connection being closed.


A first in, first out (FIFO) queue.
If maxsize is less than or equal to zero, the queue size is infinite. If it is an integer greater than 0, then await put() blocks when the queue reaches maxsize until an item is removed by get().
Unlike the standard library threading queue, the size of the queue is always known and can be returned by calling the qsize() method.
Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.
This class is not thread safe.
Number of items allowed in the queue.
Return True if the queue is empty, False otherwise.
Return True if there are maxsize items in the queue.
If the queue was initialized with maxsize=0 (the default), then full() never returns True.
Remove and return an item from the queue. If queue is empty, wait until an item is available.
Return an item if one is immediately available, else raise QueueEmpty.
Block until all items in the queue have been received and processed.
The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer coroutine calls task_done() to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks.
Put an item into the queue. If the queue is full, wait until a free slot is available before adding the item.
Put an item into the queue without blocking.
If no free slot is immediately available, raise QueueFull.
Return the number of items in the queue.
Indicate that a formerly enqueued task is complete.
Used by queue consumers. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete.
If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue).
Raises ValueError if called more times than there were items placed in the queue.


Return True if the queue is empty, False otherwise.


Return True if there are maxsize items in the queue.
If the queue was initialized with maxsize=0 (the default), then full() never returns True.


Remove and return an item from the queue. If queue is empty, wait until an item is available.


Return an item if one is immediately available, else raise QueueEmpty.


Block until all items in the queue have been received and processed.
The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer coroutine calls task_done() to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drops to zero, join() unblocks.


Put an item into the queue. If the queue is full, wait until a free slot is available before adding the item.


Put an item into the queue without blocking.
If no free slot is immediately available, raise QueueFull.


Return the number of items in the queue.


Indicate that a formerly enqueued task is complete.
Used by queue consumers. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete.
If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call was received for every item that had been put() into the queue).
Raises ValueError if called more times than there were items placed in the queue.


This exception is raised when the get_nowait() method is called on an empty queue.


Exception raised when the put_nowait() method is called on a queue that has reached its maxsize.


A base transport for read-only connections.
Instances of the ReadTransport class are returned from the loop.connect_read_pipe() event loop method and are also used by subprocess-related methods like loop.subprocess_exec().


Return True if the transport is receiving new data.
New in version 3.7.


Pause the receiving end of the transport. No data will be passed to the protocol’s protocol.data_received() method until resume_reading() is called.
Changed in version 3.7: The method is idempotent, i.e. it can be called when the transport is already paused or closed.


Resume the receiving end. The protocol’s protocol.data_received() method will be called once again if some data is available for reading.
Changed in version 3.7: The method is idempotent, i.e. it can be called when the transport is already reading.


Execute the coroutine coro and return the result.
This function runs the passed coroutine, taking care of managing the asyncio event loop, finalizing asynchronous generators, and closing the threadpool.
This function cannot be called when another asyncio event loop is running in the same thread.
If debug is True, the event loop will be run in debug mode.
This function always creates a new event loop and closes it at the end. It should be used as a main entry point for asyncio programs, and should ideally only be called once.
Example:
New in version 3.7.
Changed in version 3.9: Updated to use loop.shutdown_default_executor().
Note
The source code for asyncio.run() can be found in Lib/asyncio/runners.py.


Submit a coroutine to the given event loop. Thread-safe.
Return a concurrent.futures.Future to wait for the result from another OS thread.
This function is meant to be called from a different OS thread than the one where the event loop is running. Example:
If an exception is raised in the coroutine, the returned Future will be notified. It can also be used to cancel the task in the event loop:
See the concurrency and multithreading section of the documentation.
Unlike other asyncio functions this function requires the loop argument to be passed explicitly.
New in version 3.5.1.


This implementation uses active event loop from the main thread to handle SIGCHLD signal. If the main thread has no running event loop another thread cannot spawn a subprocess (RuntimeError is raised).
The watcher avoids disrupting other code spawning processes by polling every process explicitly on a SIGCHLD signal.
This solution is as safe as MultiLoopChildWatcher and has the same O(N) complexity but requires a running event loop in the main thread to work.


An event loop based on the selectors module.
Uses the most efficient selector available for the given platform. It is also possible to manually configure the exact selector implementation to be used:
Availability: Unix, Windows.


A Semaphore object. Not thread-safe.
A semaphore manages an internal counter which is decremented by each acquire() call and incremented by each release() call. The counter can never go below zero; when acquire() finds that it is zero, it blocks, waiting until some task calls release().
The optional value argument gives the initial value for the internal counter (1 by default). If the given value is less than 0 a ValueError is raised.
Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.
The preferred way to use a Semaphore is an async with statement:
which is equivalent to:
Acquire a semaphore.
If the internal counter is greater than zero, decrement it by one and return True immediately. If it is zero, wait until a release() is called and return True.
Returns True if semaphore can not be acquired immediately.
Release a semaphore, incrementing the internal counter by one. Can wake up a task waiting to acquire the semaphore.
Unlike BoundedSemaphore, Semaphore allows making more release() calls than acquire() calls.


Acquire a semaphore.
If the internal counter is greater than zero, decrement it by one and return True immediately. If it is zero, wait until a release() is called and return True.


Returns True if semaphore can not be acquired immediately.


Release a semaphore, incrementing the internal counter by one. Can wake up a task waiting to acquire the semaphore.
Unlike BoundedSemaphore, Semaphore allows making more release() calls than acquire() calls.


The “sendfile” syscall is not available for the given socket or file type.
A subclass of RuntimeError.


Server objects are asynchronous context managers. When used in an async with statement, it’s guaranteed that the Server object is closed and not accepting new connections when the async with statement is completed:
Changed in version 3.7: Server object is an asynchronous context manager since Python 3.7.
Stop serving: close listening sockets and set the sockets attribute to None.
The sockets that represent existing incoming client connections are left open.
The server is closed asynchronously, use the wait_closed() coroutine to wait until the server is closed.
Return the event loop associated with the server object.
New in version 3.7.
Start accepting connections.
This method is idempotent, so it can be called when the server is already being serving.
The start_serving keyword-only parameter to loop.create_server() and asyncio.start_server() allows creating a Server object that is not accepting connections initially. In this case Server.start_serving(), or Server.serve_forever() can be used to make the Server start accepting connections.
New in version 3.7.
Start accepting connections until the coroutine is cancelled. Cancellation of serve_forever task causes the server to be closed.
This method can be called if the server is already accepting connections. Only one serve_forever task can exist per one Server object.
Example:
New in version 3.7.
Return True if the server is accepting new connections.
New in version 3.7.
Wait until the close() method completes.
List of socket.socket objects the server is listening on.
Changed in version 3.7: Prior to Python 3.7 Server.sockets used to return an internal list of server sockets directly. In 3.7 a copy of that list is returned.


Stop serving: close listening sockets and set the sockets attribute to None.
The sockets that represent existing incoming client connections are left open.
The server is closed asynchronously, use the wait_closed() coroutine to wait until the server is closed.


Return the event loop associated with the server object.
New in version 3.7.


Return True if the server is accepting new connections.
New in version 3.7.


Start accepting connections until the coroutine is cancelled. Cancellation of serve_forever task causes the server to be closed.
This method can be called if the server is already accepting connections. Only one serve_forever task can exist per one Server object.
Example:
New in version 3.7.


List of socket.socket objects the server is listening on.
Changed in version 3.7: Prior to Python 3.7 Server.sockets used to return an internal list of server sockets directly. In 3.7 a copy of that list is returned.


Start accepting connections.
This method is idempotent, so it can be called when the server is already being serving.
The start_serving keyword-only parameter to loop.create_server() and asyncio.start_server() allows creating a Server object that is not accepting connections initially. In this case Server.start_serving(), or Server.serve_forever() can be used to make the Server start accepting connections.
New in version 3.7.


Wait until the close() method completes.


Set the current child watcher to watcher for the current policy. watcher must implement methods defined in the AbstractChildWatcher base class.


Set loop as a current event loop for the current OS thread.


Set the current process-wide policy to policy.
If policy is set to None, the default policy is restored.


Protect an awaitable object from being cancelled.
If aw is a coroutine it is automatically scheduled as a Task.
The statement:
is equivalent to:
except that if the coroutine containing it is cancelled, the Task running in something() is not cancelled. From the point of view of something(), the cancellation did not happen. Although its caller is still cancelled, so the “await” expression still raises a CancelledError.
If something() is cancelled by other means (i.e. from within itself) that would also cancel shield().
If it is desired to completely ignore cancellation (not recommended) the shield() function should be combined with a try/except clause, as follows:
Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.


Block for delay seconds.
If result is provided, it is returned to the caller when the coroutine completes.
sleep() always suspends the current task, allowing other tasks to run.
Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.
Example of coroutine displaying the current date every second for 5 seconds:


Start a socket server.
The client_connected_cb callback is called whenever a new client connection is established. It receives a (reader, writer) pair as two arguments, instances of the StreamReader and StreamWriter classes.
client_connected_cb can be a plain callable or a coroutine function; if it is a coroutine function, it will be automatically scheduled as a Task.
The loop argument is optional and can always be determined automatically when this method is awaited from a coroutine.
limit determines the buffer size limit used by the returned StreamReader instance. By default the limit is set to 64 KiB.
The rest of the arguments are passed directly to loop.create_server().
New in version 3.7: The ssl_handshake_timeout and start_serving parameters.


Start a Unix socket server.
Similar to start_server() but works with Unix sockets.
See also the documentation of loop.create_unix_server().
Availability: Unix.
New in version 3.7: The ssl_handshake_timeout and start_serving parameters.
Changed in version 3.7: The path parameter can now be a path-like object.