class ast.UAdd
class ast.USub
class ast.Not
class ast.Invert
Unary operator tokens. Not is the not keyword, Invert is the ~ operator. >>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))
Expression(
    body=UnaryOp(
        op=Not(),
        operand=Name(id='x', ctx=Load())))


class ast.Eq
class ast.NotEq
class ast.Lt
class ast.LtE
class ast.Gt
class ast.GtE
class ast.Is
class ast.IsNot
class ast.In
class ast.NotIn
Comparison operator tokens.


class ast.And
class ast.Or
Boolean operator tokens.


ast.parse(source, filename='<unknown>', mode='exec', *, type_comments=False, feature_version=None)
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.


class ast.Pass
A pass statement. >>> print(ast.dump(ast.parse('pass'), indent=4))
Module(
    body=[
        Pass()],
    type_ignores=[])


class ast.Add
class ast.Sub
class ast.Mult
class ast.Div
class ast.FloorDiv
class ast.Mod
class ast.Pow
class ast.LShift
class ast.RShift
class ast.BitOr
class ast.BitXor
class ast.BitAnd
class ast.MatMult
Binary operator tokens.


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


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


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


class ast.Raise(exc, cause)
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. >>> print(ast.dump(ast.parse('raise x from y'), indent=4))
Module(
    body=[
        Raise(
            exc=Name(id='x', ctx=Load()),
            cause=Name(id='y', ctx=Load()))],
    type_ignores=[])


class ast.Return(value)
A return statement. >>> print(ast.dump(ast.parse('return 4'), indent=4))
Module(
    body=[
        Return(
            value=Constant(value=4))],
    type_ignores=[])


class ast.Set(elts)
A set. elts holds a list of nodes representing the set’s elements. >>> print(ast.dump(ast.parse('{1, 2, 3}', mode='eval'), indent=4))
Expression(
    body=Set(
        elts=[
            Constant(value=1),
            Constant(value=2),
            Constant(value=3)]))


class ast.ListComp(elt, generators)
class ast.SetComp(elt, generators)
class ast.GeneratorExp(elt, generators)
class ast.DictComp(key, value, generators)
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. >>> print(ast.dump(ast.parse('[x for x in numbers]', mode='eval'), indent=4))
Expression(
    body=ListComp(
        elt=Name(id='x', ctx=Load()),
        generators=[
            comprehension(
                target=Name(id='x', ctx=Store()),
                iter=Name(id='numbers', ctx=Load()),
                ifs=[],
                is_async=0)]))
>>> print(ast.dump(ast.parse('{x: x**2 for x in numbers}', mode='eval'), indent=4))
Expression(
    body=DictComp(
        key=Name(id='x', ctx=Load()),
        value=BinOp(
            left=Name(id='x', ctx=Load()),
            op=Pow(),
            right=Constant(value=2)),
        generators=[
            comprehension(
                target=Name(id='x', ctx=Store()),
                iter=Name(id='numbers', ctx=Load()),
                ifs=[],
                is_async=0)]))
>>> print(ast.dump(ast.parse('{x for x in numbers}', mode='eval'), indent=4))
Expression(
    body=SetComp(
        elt=Name(id='x', ctx=Load()),
        generators=[
            comprehension(
                target=Name(id='x', ctx=Store()),
                iter=Name(id='numbers', ctx=Load()),
                ifs=[],
                is_async=0)]))


class ast.Slice(lower, upper, step)
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. >>> print(ast.dump(ast.parse('l[1:2]', mode='eval'), indent=4))
Expression(
    body=Subscript(
        value=Name(id='l', ctx=Load()),
        slice=Slice(
            lower=Constant(value=1),
            upper=Constant(value=2)),
        ctx=Load()))


class ast.Starred(value, ctx)
A *var variable reference. value holds the variable, typically a Name node. This type must be used when building a Call node with *args. >>> print(ast.dump(ast.parse('a, *b = it'), indent=4))
Module(
    body=[
        Assign(
            targets=[
                Tuple(
                    elts=[
                        Name(id='a', ctx=Store()),
                        Starred(
                            value=Name(id='b', ctx=Store()),
                            ctx=Store())],
                    ctx=Store())],
            value=Name(id='it', ctx=Load()))],
    type_ignores=[])


class ast.Load
class ast.Store
class ast.Del
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. >>> print(ast.dump(ast.parse('a'), indent=4))
Module(
    body=[
        Expr(
            value=Name(id='a', ctx=Load()))],
    type_ignores=[])

>>> print(ast.dump(ast.parse('a = 1'), indent=4))
Module(
    body=[
        Assign(
            targets=[
                Name(id='a', ctx=Store())],
            value=Constant(value=1))],
    type_ignores=[])

>>> print(ast.dump(ast.parse('del a'), indent=4))
Module(
    body=[
        Delete(
            targets=[
                Name(id='a', ctx=Del())])],
    type_ignores=[])


class ast.Subscript(value, slice, ctx)
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. >>> print(ast.dump(ast.parse('l[1:2, 3]', mode='eval'), indent=4))
Expression(
    body=Subscript(
        value=Name(id='l', ctx=Load()),
        slice=Tuple(
            elts=[
                Slice(
                    lower=Constant(value=1),
                    upper=Constant(value=2)),
                Constant(value=3)],
            ctx=Load()),
        ctx=Load()))


class ast.Try(body, handlers, orelse, finalbody)
try blocks. All attributes are list of nodes to execute, except for handlers, which is a list of ExceptHandler nodes. >>> print(ast.dump(ast.parse("""
... try:
...    ...
... except Exception:
...    ...
... except OtherException as e:
...    ...
... else:
...    ...
... finally:
...    ...
... """), indent=4))
Module(
    body=[
        Try(
            body=[
                Expr(
                    value=Constant(value=Ellipsis))],
            handlers=[
                ExceptHandler(
                    type=Name(id='Exception', ctx=Load()),
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))]),
                ExceptHandler(
                    type=Name(id='OtherException', ctx=Load()),
                    name='e',
                    body=[
                        Expr(
                            value=Constant(value=Ellipsis))])],
            orelse=[
                Expr(
                    value=Constant(value=Ellipsis))],
            finalbody=[
                Expr(
                    value=Constant(value=Ellipsis))])],
    type_ignores=[])


class ast.List(elts, ctx)
class ast.Tuple(elts, ctx)
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. >>> print(ast.dump(ast.parse('[1, 2, 3]', mode='eval'), indent=4))
Expression(
    body=List(
        elts=[
            Constant(value=1),
            Constant(value=2),
            Constant(value=3)],
        ctx=Load()))
>>> print(ast.dump(ast.parse('(1, 2, 3)', mode='eval'), indent=4))
Expression(
    body=Tuple(
        elts=[
            Constant(value=1),
            Constant(value=2),
            Constant(value=3)],
        ctx=Load()))


class ast.UAdd
class ast.USub
class ast.Not
class ast.Invert
Unary operator tokens. Not is the not keyword, Invert is the ~ operator. >>> print(ast.dump(ast.parse('not x', mode='eval'), indent=4))
Expression(
    body=UnaryOp(
        op=Not(),
        operand=Name(id='x', ctx=Load())))


class ast.UnaryOp(op, operand)
A unary operation. op is the operator, and operand any expression node.


ast.unparse(ast_obj)
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.


ast.walk(node)
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.


class ast.While(test, body, orelse)
A while loop. test holds the condition, such as a Compare node. >> print(ast.dump(ast.parse("""
... while x:
...    ...
... else:
...    ...
... """), indent=4))
Module(
    body=[
        While(
            test=Name(id='x', ctx=Load()),
            body=[
                Expr(
                    value=Constant(value=Ellipsis))],
            orelse=[
                Expr(
                    value=Constant(value=Ellipsis))])],
    type_ignores=[])


class ast.With(items, body, type_comment)
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
type_comment is an optional string with the type annotation as a comment.


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


class ast.withitem(context_expr, optional_vars)
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. >>> print(ast.dump(ast.parse("""\
... with a as b, c as d:
...    something(b, d)
... """), indent=4))
Module(
    body=[
        With(
            items=[
                withitem(
                    context_expr=Name(id='a', ctx=Load()),
                    optional_vars=Name(id='b', ctx=Store())),
                withitem(
                    context_expr=Name(id='c', ctx=Load()),
                    optional_vars=Name(id='d', ctx=Store()))],
            body=[
                Expr(
                    value=Call(
                        func=Name(id='something', ctx=Load()),
                        args=[
                            Name(id='b', ctx=Load()),
                            Name(id='d', ctx=Load())],
                        keywords=[]))])],
    type_ignores=[])


class ast.Yield(value)
class ast.YieldFrom(value)
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. >>> print(ast.dump(ast.parse('yield x'), indent=4))
Module(
    body=[
        Expr(
            value=Yield(
                value=Name(id='x', ctx=Load())))],
    type_ignores=[])

>>> print(ast.dump(ast.parse('yield from x'), indent=4))
Module(
    body=[
        Expr(
            value=YieldFrom(
                value=Name(id='x', ctx=Load())))],
    type_ignores=[])


asynchat — Asynchronous socket command/response handler 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.
class asynchat.async_chat
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.
ac_in_buffer_size
The asynchronous input buffer size (default 4096).

ac_out_buffer_size
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.

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

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

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

async_chat.found_terminator()
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.

async_chat.get_terminator()
Returns the current terminator for the channel.

async_chat.push(data)
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.

async_chat.push_with_producer(producer)
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.

async_chat.set_terminator(term)
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.
 asynchat Example 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. import asynchat

class http_request_handler(asynchat.async_chat):

    def __init__(self, sock, addr, sessions, log):
        asynchat.async_chat.__init__(self, sock=sock)
        self.addr = addr
        self.sessions = sessions
        self.ibuffer = []
        self.obuffer = b""
        self.set_terminator(b"\r\n\r\n")
        self.reading_headers = True
        self.handling = False
        self.cgi_data = None
        self.log = log

    def collect_incoming_data(self, data):
        """Buffer the data"""
        self.ibuffer.append(data)

    def found_terminator(self):
        if self.reading_headers:
            self.reading_headers = False
            self.parse_headers(b"".join(self.ibuffer))
            self.ibuffer = []
            if self.op.upper() == b"POST":
                clen = self.headers.getheader("content-length")
                self.set_terminator(int(clen))
            else:
                self.handling = True
                self.set_terminator(None)
                self.handle_request()
        elif not self.handling:
            self.set_terminator(None)  # browsers sometimes over-send
            self.cgi_data = parse(self.headers, b"".join(self.ibuffer))
            self.handling = True
            self.ibuffer = []
            self.handle_request()


class asynchat.async_chat
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.
ac_in_buffer_size
The asynchronous input buffer size (default 4096).

ac_out_buffer_size
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.


ac_in_buffer_size
The asynchronous input buffer size (default 4096).


ac_out_buffer_size
The asynchronous output buffer size (default 4096).


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


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


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


async_chat.found_terminator()
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.


async_chat.get_terminator()
Returns the current terminator for the channel.


async_chat.push(data)
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.


async_chat.push_with_producer(producer)
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.


async_chat.set_terminator(term)
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.


asyncio — Asynchronous I/O  Hello World! import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

# Python 3.7+
asyncio.run(main())
  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:
run Python coroutines concurrently and have full control over their execution; perform network IO and IPC; control subprocesses; distribute tasks via queues;
synchronize concurrent code;  Additionally, there are low-level APIs for library and framework developers to:  create and manage event loops, which provide asynchronous APIs for networking, running subprocesses, handling OS signals, etc; implement efficient protocols using transports;
bridge callback-based libraries and code with async/await syntax.  Reference High-level APIs  Coroutines and Tasks Streams Synchronization Primitives Subprocesses Queues Exceptions  Low-level APIs  Event Loop Futures Transports and Protocols Policies Platform Support  Guides and Tutorials  High-level API Index Low-level API Index Developing with asyncio   Note The source code for asyncio can be found in Lib/asyncio/.


class asyncio.AbstractChildWatcher

add_child_handler(pid, callback, *args)
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.

remove_child_handler(pid)
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_loop(loop)
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.

is_active()
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()
Close the watcher. This method has to be called to ensure that underlying resources are cleaned-up.


add_child_handler(pid, callback, *args)
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_loop(loop)
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()
Close the watcher. This method has to be called to ensure that underlying resources are cleaned-up.


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


remove_child_handler(pid)
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.


class asyncio.AbstractEventLoop
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.


class asyncio.AbstractEventLoopPolicy
An abstract base class for asyncio policies.
get_event_loop()
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_event_loop(loop)
Set the event loop for the current context to loop.

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

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

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


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


get_event_loop()
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.


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


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


set_event_loop(loop)
Set the event loop for the current context to loop.


asyncio.all_tasks(loop=None)
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.


asyncio.subprocess.DEVNULL
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.


asyncio.subprocess.PIPE
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.


class asyncio.subprocess.Process
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:  unlike Popen, Process instances do not have an equivalent to the poll() method; the communicate() and wait() methods don’t have a timeout parameter: use the wait_for() function; the Process.wait() method is asynchronous, whereas subprocess.Popen.wait() method is implemented as a blocking busy loop; the universal_newlines parameter is not supported.  This class is not thread safe. See also the Subprocess and Threads section.
coroutine wait()
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.

coroutine communicate(input=None)
Interact with process:  send data to stdin (if input is not None); read data from stdout and stderr, until EOF is reached; wait for process to terminate.  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.

send_signal(signal)
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.

terminate()
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()
Kill the child process. On POSIX systems this method sends SIGKILL to the child process. On Windows this method is an alias for terminate().

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

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

stderr
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.
pid
Process identification number (PID). Note that for processes created by the create_subprocess_shell() function, this attribute is the PID of the spawned shell.

returncode
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).


coroutine communicate(input=None)
Interact with process:  send data to stdin (if input is not None); read data from stdout and stderr, until EOF is reached; wait for process to terminate.  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()
Kill the child process. On POSIX systems this method sends SIGKILL to the child process. On Windows this method is an alias for terminate().


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


returncode
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).


send_signal(signal)
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.


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


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


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


terminate()
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.


coroutine wait()
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.


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


asyncio.as_completed(aws, *, loop=None, timeout=None)
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: for coro in as_completed(aws):
    earliest_result = await coro
    # ...


class asyncio.BaseProtocol
Base protocol with methods that all protocols share.


BaseProtocol.connection_lost(exc)
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.


BaseProtocol.connection_made(transport)
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.


BaseProtocol.pause_writing()
Called when the transport’s buffer goes over the high watermark.


BaseProtocol.resume_writing()
Called when the transport’s buffer drains below the low watermark.


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


BaseTransport.close()
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.


BaseTransport.get_extra_info(name, default=None)
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: sock = transport.get_extra_info('socket')
if sock is not None:
    print(sock.getsockopt(...))
 Categories of information that can be queried on some transports:
socket:
'peername': the remote address to which the socket is connected, result of socket.socket.getpeername() (None on error)
'socket': socket.socket instance
'sockname': the socket’s own address, result of socket.socket.getsockname()

SSL socket:
'compression': the compression algorithm being used as a string, or None if the connection isn’t compressed; result of ssl.SSLSocket.compression()

'cipher': a three-value tuple containing the name of the cipher being used, the version of the SSL protocol that defines its use, and the number of secret bits being used; result of ssl.SSLSocket.cipher()

'peercert': peer certificate; result of ssl.SSLSocket.getpeercert()

'sslcontext': ssl.SSLContext instance
'ssl_object': ssl.SSLObject or ssl.SSLSocket instance
pipe:
'pipe': pipe object
subprocess:
'subprocess': subprocess.Popen instance


BaseTransport.get_protocol()
Return the current protocol.


BaseTransport.is_closing()
Return True if the transport is closing or is closed.


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


class asyncio.BoundedSemaphore(value=1, *, loop=None)
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.


class asyncio.BufferedProtocol(BaseProtocol)
A base class for implementing streaming protocols with manual control of the receive buffer.


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


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


BufferedProtocol.get_buffer(sizehint)
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.


exception asyncio.CancelledError
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.


class asyncio.Condition(lock=None, *, loop=None)
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: cond = asyncio.Condition()

# ... later
async with cond:
    await cond.wait()
 which is equivalent to: cond = asyncio.Condition()

# ... later
await cond.acquire()
try:
    await cond.wait()
finally:
    cond.release()

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

notify(n=1)
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.

locked()
Return True if the underlying lock is acquired.

notify_all()
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()
Release the underlying lock. When invoked on an unlocked lock, a RuntimeError is raised.

coroutine wait()
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.

coroutine wait_for(predicate)
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.


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


locked()
Return True if the underlying lock is acquired.


notify(n=1)
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.


notify_all()
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()
Release the underlying lock. When invoked on an unlocked lock, a RuntimeError is raised.


coroutine wait()
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.


coroutine wait_for(predicate)
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.


@asyncio.coroutine
Decorator to mark generator-based coroutines. This decorator enables legacy generator-based coroutines to be compatible with async/await code: @asyncio.coroutine
def old_style_coroutine():
    yield from asyncio.sleep(1)

async def main():
    await old_style_coroutine()
 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.


coroutine asyncio.create_subprocess_exec(program, *args, stdin=None, stdout=None, stderr=None, loop=None, limit=None, **kwds)
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.


coroutine asyncio.create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None, loop=None, limit=None, **kwds)
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.


asyncio.create_task(coro, *, name=None)
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: async def coro():
    ...

# In Python 3.7+
task = asyncio.create_task(coro())
...

# This works in all Python versions but is less readable
task = asyncio.ensure_future(coro())
...
  New in version 3.7.   Changed in version 3.8: Added the name parameter.


asyncio.current_task(loop=None)
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.


class asyncio.DatagramProtocol(BaseProtocol)
The base class for implementing datagram (UDP) protocols.


DatagramProtocol.datagram_received(data, addr)
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.


DatagramProtocol.error_received(exc)
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.


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


DatagramTransport.abort()
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.


DatagramTransport.sendto(data, addr=None)
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.


class asyncio.DefaultEventLoopPolicy
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.


asyncio.ensure_future(obj, *, loop=None)
Return:
obj argument as is, if obj is a Future, a Task, or a Future-like object (isfuture() is used for the test.) a Task object wrapping obj, if obj is a coroutine (iscoroutine() is used for the test); in this case the coroutine will be scheduled by ensure_future(). a Task object that would await on obj, if obj is an awaitable (inspect.isawaitable() is used for the test.)  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.


class asyncio.Event(*, loop=None)
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: async def waiter(event):
    print('waiting for it ...')
    await event.wait()
    print('... got it!')

async def main():
    # Create an Event object.
    event = asyncio.Event()

    # Spawn a Task to wait until 'event' is set.
    waiter_task = asyncio.create_task(waiter(event))

    # Sleep for 1 second and set the event.
    await asyncio.sleep(1)
    event.set()

    # Wait until the waiter task is finished.
    await waiter_task

asyncio.run(main())

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

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

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

is_set()
Return True if the event is set.


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


is_set()
Return True if the event is set.


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


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


class asyncio.FastChildWatcher
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.


class asyncio.Future(*, loop=None)
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.
result()
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.

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

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

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.

cancelled()
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: if not fut.cancelled():
    fut.set_result(42)

add_done_callback(callback, *, context=None)
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.: # Call 'print("Future:", fut)' when "fut" is done.
fut.add_done_callback(
    functools.partial(print, "Future:"))
  Changed in version 3.7: The context keyword-only parameter was added. See PEP 567 for more details.

remove_done_callback(callback)
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(msg=None)
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.

exception()
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.

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


add_done_callback(callback, *, context=None)
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.: # Call 'print("Future:", fut)' when "fut" is done.
fut.add_done_callback(
    functools.partial(print, "Future:"))
  Changed in version 3.7: The context keyword-only parameter was added. See PEP 567 for more details.


cancel(msg=None)
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.


cancelled()
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: if not fut.cancelled():
    fut.set_result(42)


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.


exception()
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.


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


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


result()
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.


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


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


awaitable asyncio.gather(*aws, loop=None, return_exceptions=False)
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: import asyncio

async def factorial(name, number):
    f = 1
    for i in range(2, number + 1):
        print(f"Task {name}: Compute factorial({i})...")
        await asyncio.sleep(1)
        f *= i
    print(f"Task {name}: factorial({number}) = {f}")

async def main():
    # Schedule three calls *concurrently*:
    await asyncio.gather(
        factorial("A", 2),
        factorial("B", 3),
        factorial("C", 4),
    )

asyncio.run(main())

# Expected output:
#
#     Task A: Compute factorial(2)...
#     Task B: Compute factorial(2)...
#     Task C: Compute factorial(2)...
#     Task A: factorial(2) = 2
#     Task B: Compute factorial(3)...
#     Task C: Compute factorial(3)...
#     Task B: factorial(3) = 6
#     Task C: Compute factorial(4)...
#     Task C: factorial(4) = 24
  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.


asyncio.get_child_watcher()
Return the current child watcher for the current policy.


asyncio.get_event_loop()
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.


asyncio.get_event_loop_policy()
Return the current process-wide policy.


asyncio.get_running_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.


class asyncio.Handle
A callback wrapper object returned by loop.call_soon(), loop.call_soon_threadsafe().
cancel()
Cancel the callback. If the callback has already been canceled or executed, this method has no effect.

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


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


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


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

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


expected
The total number (int) of expected bytes.


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


exception asyncio.InvalidStateError
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.


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


asyncio.iscoroutinefunction(func)
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.


asyncio.isfuture(obj)
Return True if obj is either of:  an instance of asyncio.Future, an instance of asyncio.Task, a Future-like object with a _asyncio_future_blocking attribute.   New in version 3.5.


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


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


consumed
The total number of to be consumed bytes.


class asyncio.Lock(*, loop=None)
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: lock = asyncio.Lock()

# ... later
async with lock:
    # access shared state
 which is equivalent to: lock = asyncio.Lock()

# ... later
await lock.acquire()
try:
    # access shared state
finally:
    lock.release()
  Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.
coroutine acquire()
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()
Release the lock. When the lock is locked, reset it to unlocked and return. If the lock is unlocked, a RuntimeError is raised.

locked()
Return True if the lock is locked.


coroutine acquire()
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.


locked()
Return True if the lock is locked.


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


loop.add_reader(fd, callback, *args)
Start monitoring the fd file descriptor for read availability and invoke callback with the specified arguments once fd is available for reading.


loop.add_signal_handler(signum, callback, *args)
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.


loop.add_writer(fd, callback, *args)
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.


loop.call_at(when, callback, *args, context=None)
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.


loop.call_exception_handler(context)
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):  ‘message’: Error message; ‘exception’ (optional): Exception object; ‘future’ (optional): asyncio.Future instance; ‘handle’ (optional): asyncio.Handle instance; ‘protocol’ (optional): Protocol instance; ‘transport’ (optional): Transport instance; ‘socket’ (optional): socket.socket instance.   Note This method should not be overloaded in subclassed event loops. For custom exception handling, use the set_exception_handler() method.


loop.call_later(delay, callback, *args, context=None)
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.


loop.call_soon(callback, *args, context=None)
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.


loop.call_soon_threadsafe(callback, *args, context=None)
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.


loop.close()
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.


coroutine loop.connect_accepted_socket(protocol_factory, sock, *, ssl=None, ssl_handshake_timeout=None)
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:
protocol_factory must be a callable returning a protocol implementation.
sock is a preexisting socket object returned from socket.accept.
ssl can be set to an SSLContext to enable SSL over the accepted connections.
ssl_handshake_timeout is (for an SSL connection) the time in seconds to wait for the SSL handshake to complete before aborting the connection. 60.0 seconds if None (default).  Returns a (transport, protocol) pair.  New in version 3.7: The ssl_handshake_timeout parameter.   New in version 3.5.3.


coroutine loop.connect_read_pipe(protocol_factory, pipe)
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.


coroutine loop.connect_write_pipe(protocol_factory, pipe)
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.


coroutine loop.create_connection(protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, happy_eyeballs_delay=None, interleave=None)
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 connection is established and a transport is created for it.
protocol_factory is called without arguments and is expected to return a protocol instance. The protocol instance is coupled with the transport by calling its connection_made() method. A (transport, protocol) tuple is returned on success.  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
server_hostname sets or overrides the hostname that the target server’s certificate will be matched against. Should only be passed if ssl is not None. By default the value of the host argument is used. If host is empty, there is no default and you must pass a value for server_hostname. If server_hostname is an empty string, hostname matching is disabled (which is a serious security risk, allowing for potential man-in-the-middle attacks).
family, proto, flags are the optional address family, protocol and flags to be passed through to getaddrinfo() for host resolution. If given, these should all be integers from the corresponding socket module constants.
happy_eyeballs_delay, if given, enables Happy Eyeballs for this connection. It should be a floating-point number representing the amount of time in seconds to wait for a connection attempt to complete, before starting the next attempt in parallel. This is the “Connection Attempt Delay” as defined in RFC 8305. A sensible default value recommended by the RFC is 0.25 (250 milliseconds).
interleave controls address reordering when a host name resolves to multiple IP addresses. If 0 or unspecified, no reordering is done, and addresses are tried in the order returned by getaddrinfo(). If a positive integer is specified, the addresses are interleaved by address family, and the given integer is interpreted as “First Address Family Count” as defined in RFC 8305. The default is 0 if happy_eyeballs_delay is not specified, and 1 if it is.
sock, if given, should be an existing, already connected socket.socket object to be used by the transport. If sock is given, none of host, port, family, proto, flags, happy_eyeballs_delay, interleave and local_addr should be specified.
local_addr, if given, is a (local_host, local_port) tuple used to bind the socket to locally. The local_host and local_port are looked up using getaddrinfo(), similarly to host and port.
ssl_handshake_timeout is (for a TLS connection) the time in seconds to wait for the TLS handshake to complete before aborting the connection. 60.0 seconds if None (default).   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.


coroutine loop.create_datagram_endpoint(protocol_factory, local_addr=None, remote_addr=None, *, family=0, proto=0, flags=0, reuse_address=None, reuse_port=None, allow_broadcast=None, sock=None)
 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:
local_addr, if given, is a (local_host, local_port) tuple used to bind the socket to locally. The local_host and local_port are looked up using getaddrinfo().
remote_addr, if given, is a (remote_host, remote_port) tuple used to connect the socket to a remote address. The remote_host and remote_port are looked up using getaddrinfo().
family, proto, flags are the optional address family, protocol and flags to be passed through to getaddrinfo() for host resolution. If given, these should all be integers from the corresponding socket module constants.
reuse_port tells the kernel to allow this endpoint to be bound to the same port as other existing endpoints are bound to, so long as they all set this flag when being created. This option is not supported on Windows and some Unixes. If the SO_REUSEPORT constant is not defined then this capability is unsupported.
allow_broadcast tells the kernel to allow this endpoint to send messages to the broadcast address.
sock can optionally be specified in order to use a preexisting, already connected, socket.socket object to be used by the transport. If specified, local_addr and remote_addr should be omitted (must be None).  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.


loop.create_future()
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.


coroutine loop.create_server(protocol_factory, host=None, port=None, *, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None, ssl_handshake_timeout=None, start_serving=True)
Create a TCP server (socket type SOCK_STREAM) listening on port of the host address. Returns a Server object. Arguments:
protocol_factory must be a callable returning a protocol implementation.
The host parameter can be set to several types which determine where the server would be listening:  If host is a string, the TCP server is bound to a single network interface specified by host. If host is a sequence of strings, the TCP server is bound to all network interfaces specified by the sequence. If host is an empty string or None, all interfaces are assumed and a list of multiple sockets will be returned (most likely one for IPv4 and another one for IPv6).
family can be set to either socket.AF_INET or AF_INET6 to force the socket to use IPv4 or IPv6. If not set, the family will be determined from host name (defaults to AF_UNSPEC).
flags is a bitmask for getaddrinfo().
sock can optionally be specified in order to use a preexisting socket object. If specified, host and port must not be specified.
backlog is the maximum number of queued connections passed to listen() (defaults to 100).
ssl can be set to an SSLContext instance to enable TLS over the accepted connections.
reuse_address tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire. If not specified will automatically be set to True on Unix.
reuse_port tells the kernel to allow this endpoint to be bound to the same port as other existing endpoints are bound to, so long as they all set this flag when being created. This option is not supported on Windows.
ssl_handshake_timeout is (for a TLS server) the time in seconds to wait for the TLS handshake to complete before aborting the connection. 60.0 seconds if None (default).
start_serving set to True (the default) causes the created server to start accepting connections immediately. When set to False, the user should await on Server.start_serving() or Server.serve_forever() to make the server to start accepting connections.   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.


loop.create_task(coro, *, name=None)
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.


coroutine loop.create_unix_connection(protocol_factory, path=None, *, ssl=None, sock=None, server_hostname=None, ssl_handshake_timeout=None)
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.


coroutine loop.create_unix_server(protocol_factory, path=None, *, sock=None, backlog=100, ssl=None, ssl_handshake_timeout=None, start_serving=True)
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.


loop.default_exception_handler(context)
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().


coroutine loop.getaddrinfo(host, port, *, family=0, type=0, proto=0, flags=0)
Asynchronous version of socket.getaddrinfo().


coroutine loop.getnameinfo(sockaddr, flags=0)
Asynchronous version of socket.getnameinfo().


loop.get_debug()
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.


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


loop.get_task_factory()
Return a task factory or None if the default one is in use.


loop.is_closed()
Return True if the event loop was closed.


loop.is_running()
Return True if the event loop is currently running.


loop.remove_reader(fd)
Stop monitoring the fd file descriptor for read availability.


loop.remove_signal_handler(sig)
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.


loop.remove_writer(fd)
Stop monitoring the fd file descriptor for write availability.


loop.run_forever()
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.


awaitable loop.run_in_executor(executor, func, *args)
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: import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

asyncio.run(main())
 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.


loop.run_until_complete(future)
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.


coroutine loop.sendfile(transport, file, offset=0, count=None, *, fallback=True)
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.


loop.set_debug(enabled: bool)
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.


loop.set_default_executor(executor)
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.


loop.set_exception_handler(handler)
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).


loop.set_task_factory(factory)
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.


coroutine loop.shutdown_asyncgens()
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: try:
    loop.run_forever()
finally:
    loop.run_until_complete(loop.shutdown_asyncgens())
    loop.close()
  New in version 3.6.


coroutine loop.shutdown_default_executor()
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.


coroutine loop.sock_accept(sock)
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().


coroutine loop.sock_connect(sock, address)
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().


coroutine loop.sock_recv(sock, nbytes)
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.


coroutine loop.sock_recv_into(sock, buf)
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.


coroutine loop.sock_sendall(sock, data)
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.


coroutine loop.sock_sendfile(sock, file, offset=0, count=None, *, fallback=True)
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.


coroutine loop.start_tls(transport, protocol, sslcontext, *, server_side=False, server_hostname=None, ssl_handshake_timeout=None)
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:
transport and protocol instances that methods like create_server() and create_connection() return.
sslcontext: a configured instance of SSLContext.
server_side pass True when a server-side connection is being upgraded (like the one created by create_server()).
server_hostname: sets or overrides the host name that the target server’s certificate will be matched against.
ssl_handshake_timeout is (for a TLS connection) the time in seconds to wait for the TLS handshake to complete before aborting the connection. 60.0 seconds if None (default).   New in version 3.7.


coroutine loop.subprocess_exec(protocol_factory, *args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
Create a subprocess from one or more string arguments specified by args. args must be a list of strings represented by:
str; or bytes, encoded to the filesystem encoding.  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:  a file-like object representing a pipe to be connected to the subprocess’s standard input stream using connect_write_pipe()
 the subprocess.PIPE constant (default) which will create a new pipe and connect it, the value None which will make the subprocess inherit the file descriptor from this process the subprocess.DEVNULL constant which indicates that the special os.devnull file will be used
stdout can be any of these:  a file-like object representing a pipe to be connected to the subprocess’s standard output stream using connect_write_pipe()
 the subprocess.PIPE constant (default) which will create a new pipe and connect it, the value None which will make the subprocess inherit the file descriptor from this process the subprocess.DEVNULL constant which indicates that the special os.devnull file will be used
stderr can be any of these:  a file-like object representing a pipe to be connected to the subprocess’s standard error stream using connect_write_pipe()
 the subprocess.PIPE constant (default) which will create a new pipe and connect it, the value None which will make the subprocess inherit the file descriptor from this process the subprocess.DEVNULL constant which indicates that the special os.devnull file will be used the subprocess.STDOUT constant which will connect the standard error stream to the process’ standard output stream
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.


coroutine loop.subprocess_shell(protocol_factory, cmd, *, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
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.


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


class asyncio.MultiLoopChildWatcher
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.


asyncio.new_event_loop()
Create a new event loop object.


coroutine asyncio.open_connection(host=None, port=None, *, loop=None, limit=None, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None)
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.


coroutine asyncio.open_unix_connection(path=None, *, loop=None, limit=None, ssl=None, sock=None, server_hostname=None, ssl_handshake_timeout=None)
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