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


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


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


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


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


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


class asyncio.Queue(maxsize=0, *, loop=None)
A first in, first out (FIFO) queue. If maxsize is less than or equal to zero, the queue size is infinite. If it is an integer greater than 0, then await put() blocks when the queue reaches maxsize until an item is removed by get(). Unlike the standard library threading queue, the size of the queue is always known and can be returned by calling the qsize() method.  Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.  This class is not thread safe.
maxsize
Number of items allowed in the queue.

empty()
Return True if the queue is empty, False otherwise.

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

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

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

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

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

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

qsize()
Return the number of items in the queue.

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


empty()
Return True if the queue is empty, False otherwise.


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


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


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


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


maxsize
Number of items allowed in the queue.


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


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


qsize()
Return the number of items in the queue.


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


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


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


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


ReadTransport.is_reading()
Return True if the transport is receiving new data.  New in version 3.7.


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


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


asyncio.run(coro, *, debug=False)
Execute the coroutine coro and return the result. This function runs the passed coroutine, taking care of managing the asyncio event loop, finalizing asynchronous generators, and closing the threadpool. This function cannot be called when another asyncio event loop is running in the same thread. If debug is True, the event loop will be run in debug mode. This function always creates a new event loop and closes it at the end. It should be used as a main entry point for asyncio programs, and should ideally only be called once. Example: async def main():
    await asyncio.sleep(1)
    print('hello')

asyncio.run(main())
  New in version 3.7.   Changed in version 3.9: Updated to use loop.shutdown_default_executor().   Note The source code for asyncio.run() can be found in Lib/asyncio/runners.py.


asyncio.run_coroutine_threadsafe(coro, loop)
Submit a coroutine to the given event loop. Thread-safe. Return a concurrent.futures.Future to wait for the result from another OS thread. This function is meant to be called from a different OS thread than the one where the event loop is running. Example: # Create a coroutine
coro = asyncio.sleep(1, result=3)

# Submit the coroutine to a given loop
future = asyncio.run_coroutine_threadsafe(coro, loop)

# Wait for the result with an optional timeout argument
assert future.result(timeout) == 3
 If an exception is raised in the coroutine, the returned Future will be notified. It can also be used to cancel the task in the event loop: try:
    result = future.result(timeout)
except asyncio.TimeoutError:
    print('The coroutine took too long, cancelling the task...')
    future.cancel()
except Exception as exc:
    print(f'The coroutine raised an exception: {exc!r}')
else:
    print(f'The coroutine returned: {result!r}')
 See the concurrency and multithreading section of the documentation. Unlike other asyncio functions this function requires the loop argument to be passed explicitly.  New in version 3.5.1.


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


class asyncio.SelectorEventLoop
An event loop based on the selectors module. Uses the most efficient selector available for the given platform. It is also possible to manually configure the exact selector implementation to be used: import asyncio
import selectors

selector = selectors.SelectSelector()
loop = asyncio.SelectorEventLoop(selector)
asyncio.set_event_loop(loop)
 Availability: Unix, Windows.


class asyncio.Semaphore(value=1, *, loop=None)
A Semaphore object. Not thread-safe. A semaphore manages an internal counter which is decremented by each acquire() call and incremented by each release() call. The counter can never go below zero; when acquire() finds that it is zero, it blocks, waiting until some task calls release(). The optional value argument gives the initial value for the internal counter (1 by default). If the given value is less than 0 a ValueError is raised.  Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.  The preferred way to use a Semaphore is an async with statement: sem = asyncio.Semaphore(10)

# ... later
async with sem:
    # work with shared resource
 which is equivalent to: sem = asyncio.Semaphore(10)

# ... later
await sem.acquire()
try:
    # work with shared resource
finally:
    sem.release()

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

locked()
Returns True if semaphore can not be acquired immediately.

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


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


locked()
Returns True if semaphore can not be acquired immediately.


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


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


class asyncio.Server
Server objects are asynchronous context managers. When used in an async with statement, it’s guaranteed that the Server object is closed and not accepting new connections when the async with statement is completed: srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
  Changed in version 3.7: Server object is an asynchronous context manager since Python 3.7.
close()
Stop serving: close listening sockets and set the sockets attribute to None. The sockets that represent existing incoming client connections are left open. The server is closed asynchronously, use the wait_closed() coroutine to wait until the server is closed.

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

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

coroutine serve_forever()
Start accepting connections until the coroutine is cancelled. Cancellation of serve_forever task causes the server to be closed. This method can be called if the server is already accepting connections. Only one serve_forever task can exist per one Server object. Example: async def client_connected(reader, writer):
    # Communicate with the client with
    # reader/writer streams.  For example:
    await reader.readline()

async def main(host, port):
    srv = await asyncio.start_server(
        client_connected, host, port)
    await srv.serve_forever()

asyncio.run(main('127.0.0.1', 0))
  New in version 3.7.

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

coroutine wait_closed()
Wait until the close() method completes.

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


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


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


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


coroutine serve_forever()
Start accepting connections until the coroutine is cancelled. Cancellation of serve_forever task causes the server to be closed. This method can be called if the server is already accepting connections. Only one serve_forever task can exist per one Server object. Example: async def client_connected(reader, writer):
    # Communicate with the client with
    # reader/writer streams.  For example:
    await reader.readline()

async def main(host, port):
    srv = await asyncio.start_server(
        client_connected, host, port)
    await srv.serve_forever()

asyncio.run(main('127.0.0.1', 0))
  New in version 3.7.


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


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


coroutine wait_closed()
Wait until the close() method completes.


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


asyncio.set_event_loop(loop)
Set loop as a current event loop for the current OS thread.


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


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


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

async def display_date():
    loop = asyncio.get_running_loop()
    end_time = loop.time() + 5.0
    while True:
        print(datetime.datetime.now())
        if (loop.time() + 1.0) >= end_time:
            break
        await asyncio.sleep(1)

asyncio.run(display_date())


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


coroutine asyncio.start_unix_server(client_connected_cb, path=None, *, loop=None, limit=None, sock=None, backlog=100, ssl=None, ssl_handshake_timeout=None, start_serving=True)
Start a Unix socket server. Similar to start_server() but works with Unix sockets. See also the documentation of loop.create_unix_server(). Availability: Unix.  New in version 3.7: The ssl_handshake_timeout and start_serving parameters.   Changed in version 3.7: The path parameter can now be a path-like object.


class asyncio.StreamReader
Represents a reader object that provides APIs to read data from the IO stream. It is not recommended to instantiate StreamReader objects directly; use open_connection() and start_server() instead.
coroutine read(n=-1)
Read up to n bytes. If n is not provided, or set to -1, read until EOF and return all read bytes. If EOF was received and the internal buffer is empty, return an empty bytes object.

coroutine readline()
Read one line, where “line” is a sequence of bytes ending with \n. If EOF is received and \n was not found, the method returns partially read data. If EOF is received and the internal buffer is empty, return an empty bytes object.

coroutine readexactly(n)
Read exactly n bytes. Raise an IncompleteReadError if EOF is reached before n can be read. Use the IncompleteReadError.partial attribute to get the partially read data.

coroutine readuntil(separator=b'\n')
Read data from the stream until separator is found. On success, the data and separator will be removed from the internal buffer (consumed). Returned data will include the separator at the end. If the amount of data read exceeds the configured stream limit, a LimitOverrunError exception is raised, and the data is left in the internal buffer and can be read again. If EOF is reached before the complete separator is found, an IncompleteReadError exception is raised, and the internal buffer is reset. The IncompleteReadError.partial attribute may contain a portion of the separator.  New in version 3.5.2.

at_eof()
Return True if the buffer is empty and feed_eof() was called.


at_eof()
Return True if the buffer is empty and feed_eof() was called.


coroutine read(n=-1)
Read up to n bytes. If n is not provided, or set to -1, read until EOF and return all read bytes. If EOF was received and the internal buffer is empty, return an empty bytes object.


coroutine readexactly(n)
Read exactly n bytes. Raise an IncompleteReadError if EOF is reached before n can be read. Use the IncompleteReadError.partial attribute to get the partially read data.


coroutine readline()
Read one line, where “line” is a sequence of bytes ending with \n. If EOF is received and \n was not found, the method returns partially read data. If EOF is received and the internal buffer is empty, return an empty bytes object.


coroutine readuntil(separator=b'\n')
Read data from the stream until separator is found. On success, the data and separator will be removed from the internal buffer (consumed). Returned data will include the separator at the end. If the amount of data read exceeds the configured stream limit, a LimitOverrunError exception is raised, and the data is left in the internal buffer and can be read again. If EOF is reached before the complete separator is found, an IncompleteReadError exception is raised, and the internal buffer is reset. The IncompleteReadError.partial attribute may contain a portion of the separator.  New in version 3.5.2.


class asyncio.StreamWriter
Represents a writer object that provides APIs to write data to the IO stream. It is not recommended to instantiate StreamWriter objects directly; use open_connection() and start_server() instead.
write(data)
The method attempts to write the data to the underlying socket immediately. If that fails, the data is queued in an internal write buffer until it can be sent. The method should be used along with the drain() method: stream.write(data)
await stream.drain()

writelines(data)
The method writes a list (or any iterable) of bytes to the underlying socket immediately. If that fails, the data is queued in an internal write buffer until it can be sent. The method should be used along with the drain() method: stream.writelines(lines)
await stream.drain()

close()
The method closes the stream and the underlying socket. The method should be used along with the wait_closed() method: stream.close()
await stream.wait_closed()

can_write_eof()
Return True if the underlying transport supports the write_eof() method, False otherwise.

write_eof()
Close the write end of the stream after the buffered write data is flushed.

transport
Return the underlying asyncio transport.

get_extra_info(name, default=None)
Access optional transport information; see BaseTransport.get_extra_info() for details.

coroutine drain()
Wait until it is appropriate to resume writing to the stream. Example: writer.write(data)
await writer.drain()
 This is a flow control method that interacts with the underlying IO write buffer. When the size of the buffer reaches the high watermark, drain() blocks until the size of the buffer is drained down to the low watermark and writing can be resumed. When there is nothing to wait for, the drain() returns immediately.

is_closing()
Return True if the stream is closed or in the process of being closed.  New in version 3.7.

coroutine wait_closed()
Wait until the stream is closed. Should be called after close() to wait until the underlying connection is closed.  New in version 3.7.


can_write_eof()
Return True if the underlying transport supports the write_eof() method, False otherwise.


close()
The method closes the stream and the underlying socket. The method should be used along with the wait_closed() method: stream.close()
await stream.wait_closed()


coroutine drain()
Wait until it is appropriate to resume writing to the stream. Example: writer.write(data)
await writer.drain()
 This is a flow control method that interacts with the underlying IO write buffer. When the size of the buffer reaches the high watermark, drain() blocks until the size of the buffer is drained down to the low watermark and writing can be resumed. When there is nothing to wait for, the drain() returns immediately.


get_extra_info(name, default=None)
Access optional transport information; see BaseTransport.get_extra_info() for details.


is_closing()
Return True if the stream is closed or in the process of being closed.  New in version 3.7.


transport
Return the underlying asyncio transport.


coroutine wait_closed()
Wait until the stream is closed. Should be called after close() to wait until the underlying connection is closed.  New in version 3.7.


write(data)
The method attempts to write the data to the underlying socket immediately. If that fails, the data is queued in an internal write buffer until it can be sent. The method should be used along with the drain() method: stream.write(data)
await stream.drain()


writelines(data)
The method writes a list (or any iterable) of bytes to the underlying socket immediately. If that fails, the data is queued in an internal write buffer until it can be sent. The method should be used along with the drain() method: stream.writelines(lines)
await stream.drain()


write_eof()
Close the write end of the stream after the buffered write data is flushed.


class asyncio.SubprocessProtocol(BaseProtocol)
The base class for implementing protocols communicating with child processes (unidirectional pipes).


SubprocessProtocol.pipe_connection_lost(fd, exc)
Called when one of the pipes communicating with the child process is closed. fd is the integer file descriptor that was closed.


SubprocessProtocol.pipe_data_received(fd, data)
Called when the child process writes data into its stdout or stderr pipe. fd is the integer file descriptor of the pipe. data is a non-empty bytes object containing the received data.


SubprocessProtocol.process_exited()
Called when the child process has exited.


class asyncio.SubprocessTransport(BaseTransport)
An abstraction to represent a connection between a parent and its child OS process. Instances of the SubprocessTransport class are returned from event loop methods loop.subprocess_shell() and loop.subprocess_exec().


SubprocessTransport.close()
Kill the subprocess by calling the kill() method. If the subprocess hasn’t returned yet, and close transports of stdin, stdout, and stderr pipes.


SubprocessTransport.get_pid()
Return the subprocess process id as an integer.


SubprocessTransport.get_pipe_transport(fd)
Return the transport for the communication pipe corresponding to the integer file descriptor fd:
0: readable streaming transport of the standard input (stdin), or None if the subprocess was not created with stdin=PIPE

1: writable streaming transport of the standard output (stdout), or None if the subprocess was not created with stdout=PIPE

2: writable streaming transport of the standard error (stderr), or None if the subprocess was not created with stderr=PIPE
 other fd: None


SubprocessTransport.get_returncode()
Return the subprocess return code as an integer or None if it hasn’t returned, which is similar to the subprocess.Popen.returncode attribute.


SubprocessTransport.kill()
Kill the subprocess. On POSIX systems, the function sends SIGKILL to the subprocess. On Windows, this method is an alias for terminate(). See also subprocess.Popen.kill().


SubprocessTransport.send_signal(signal)
Send the signal number to the subprocess, as in subprocess.Popen.send_signal().


SubprocessTransport.terminate()
Stop the subprocess. On POSIX systems, this method sends SIGTERM to the subprocess. On Windows, the Windows API function TerminateProcess() is called to stop the subprocess. See also subprocess.Popen.terminate().


class asyncio.Task(coro, *, loop=None, name=None)
A Future-like object that runs a Python coroutine. Not thread-safe. Tasks are used to run coroutines in event loops. If a coroutine awaits on a Future, the Task suspends the execution of the coroutine and waits for the completion of the Future. When the Future is done, the execution of the wrapped coroutine resumes. Event loops use cooperative scheduling: an event loop runs one Task at a time. While a Task awaits for the completion of a Future, the event loop runs other Tasks, callbacks, or performs IO operations. Use the high-level asyncio.create_task() function to create Tasks, or the low-level loop.create_task() or ensure_future() functions. Manual instantiation of Tasks is discouraged. To cancel a running Task use the cancel() method. Calling it will cause the Task to throw a CancelledError exception into the wrapped coroutine. If a coroutine is awaiting on a Future object during cancellation, the Future object will be cancelled. cancelled() can be used to check if the Task was cancelled. The method returns True if the wrapped coroutine did not suppress the CancelledError exception and was actually cancelled. asyncio.Task inherits from Future all of its APIs except Future.set_result() and Future.set_exception(). Tasks support the contextvars module. When a Task is created it copies the current context and later runs its coroutine in the copied context.  Changed in version 3.7: Added support for the contextvars module.   Changed in version 3.8: Added the name parameter.   Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.
cancel(msg=None)
Request the Task to be cancelled. This arranges for a CancelledError exception to be thrown into the wrapped coroutine on the next cycle of the event loop. The coroutine then has a chance to clean up or even deny the request by suppressing the exception with a try … … except CancelledError … finally block. Therefore, unlike Future.cancel(), Task.cancel() does not guarantee that the Task will be cancelled, although suppressing cancellation completely is not common and is actively discouraged.  Changed in version 3.9: Added the msg parameter.  The following example illustrates how coroutines can intercept the cancellation request: async def cancel_me():
    print('cancel_me(): before sleep')

    try:
        # Wait for 1 hour
        await asyncio.sleep(3600)
    except asyncio.CancelledError:
        print('cancel_me(): cancel sleep')
        raise
    finally:
        print('cancel_me(): after sleep')

async def main():
    # Create a "cancel_me" Task
    task = asyncio.create_task(cancel_me())

    # Wait for 1 second
    await asyncio.sleep(1)

    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("main(): cancel_me is cancelled now")

asyncio.run(main())

# Expected output:
#
#     cancel_me(): before sleep
#     cancel_me(): cancel sleep
#     cancel_me(): after sleep
#     main(): cancel_me is cancelled now

cancelled()
Return True if the Task is cancelled. The Task is cancelled when the cancellation was requested with cancel() and the wrapped coroutine propagated the CancelledError exception thrown into it.

done()
Return True if the Task is done. A Task is done when the wrapped coroutine either returned a value, raised an exception, or the Task was cancelled.

result()
Return the result of the Task. If the Task is done, the result of the wrapped coroutine is returned (or if the coroutine raised an exception, that exception is re-raised.) If the Task has been cancelled, this method raises a CancelledError exception. If the Task’s result isn’t yet available, this method raises a InvalidStateError exception.

exception()
Return the exception of the Task. If the wrapped coroutine raised an exception that exception is returned. If the wrapped coroutine returned normally this method returns None. If the Task has been cancelled, this method raises a CancelledError exception. If the Task isn’t done yet, this method raises an InvalidStateError exception.

add_done_callback(callback, *, context=None)
Add a callback to be run when the Task is done. This method should only be used in low-level callback-based code. See the documentation of Future.add_done_callback() for more details.

remove_done_callback(callback)
Remove callback from the callbacks list. This method should only be used in low-level callback-based code. See the documentation of Future.remove_done_callback() for more details.

get_stack(*, limit=None)
Return the list of stack frames for this Task. If the wrapped coroutine is not done, this returns the stack where it is suspended. If the coroutine has completed successfully or was cancelled, this returns an empty list. If the coroutine was terminated by an exception, this returns the list of traceback frames. The frames are always ordered from oldest to newest. Only one stack frame is returned for a suspended coroutine. The optional limit argument sets the maximum number of frames to return; by default all available frames are returned. The ordering of the returned list differs depending on whether a stack or a traceback is returned: the newest frames of a stack are returned, but the oldest frames of a traceback are returned. (This matches the behavior of the traceback module.)

print_stack(*, limit=None, file=None)
Print the stack or traceback for this Task. This produces output similar to that of the traceback module for the frames retrieved by get_stack(). The limit argument is passed to get_stack() directly. The file argument is an I/O stream to which the output is written; by default output is written to sys.stderr.

get_coro()
Return the coroutine object wrapped by the Task.  New in version 3.8.

get_name()
Return the name of the Task. If no name has been explicitly assigned to the Task, the default asyncio Task implementation generates a default name during instantiation.  New in version 3.8.

set_name(value)
Set the name of the Task. The value argument can be any object, which is then converted to a string. In the default Task implementation, the name will be visible in the repr() output of a task object.  New in version 3.8.


add_done_callback(callback, *, context=None)
Add a callback to be run when the Task is done. This method should only be used in low-level callback-based code. See the documentation of Future.add_done_callback() for more details.


cancel(msg=None)
Request the Task to be cancelled. This arranges for a CancelledError exception to be thrown into the wrapped coroutine on the next cycle of the event loop. The coroutine then has a chance to clean up or even deny the request by suppressing the exception with a try … … except CancelledError … finally block. Therefore, unlike Future.cancel(), Task.cancel() does not guarantee that the Task will be cancelled, although suppressing cancellation completely is not common and is actively discouraged.  Changed in version 3.9: Added the msg parameter.  The following example illustrates how coroutines can intercept the cancellation request: async def cancel_me():
    print('cancel_me(): before sleep')

    try:
        # Wait for 1 hour
        await asyncio.sleep(3600)
    except asyncio.CancelledError:
        print('cancel_me(): cancel sleep')
        raise
    finally:
        print('cancel_me(): after sleep')

async def main():
    # Create a "cancel_me" Task
    task = asyncio.create_task(cancel_me())

    # Wait for 1 second
    await asyncio.sleep(1)

    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("main(): cancel_me is cancelled now")

asyncio.run(main())

# Expected output:
#
#     cancel_me(): before sleep
#     cancel_me(): cancel sleep
#     cancel_me(): after sleep
#     main(): cancel_me is cancelled now


cancelled()
Return True if the Task is cancelled. The Task is cancelled when the cancellation was requested with cancel() and the wrapped coroutine propagated the CancelledError exception thrown into it.


done()
Return True if the Task is done. A Task is done when the wrapped coroutine either returned a value, raised an exception, or the Task was cancelled.


exception()
Return the exception of the Task. If the wrapped coroutine raised an exception that exception is returned. If the wrapped coroutine returned normally this method returns None. If the Task has been cancelled, this method raises a CancelledError exception. If the Task isn’t done yet, this method raises an InvalidStateError exception.


get_coro()
Return the coroutine object wrapped by the Task.  New in version 3.8.


get_name()
Return the name of the Task. If no name has been explicitly assigned to the Task, the default asyncio Task implementation generates a default name during instantiation.  New in version 3.8.


get_stack(*, limit=None)
Return the list of stack frames for this Task. If the wrapped coroutine is not done, this returns the stack where it is suspended. If the coroutine has completed successfully or was cancelled, this returns an empty list. If the coroutine was terminated by an exception, this returns the list of traceback frames. The frames are always ordered from oldest to newest. Only one stack frame is returned for a suspended coroutine. The optional limit argument sets the maximum number of frames to return; by default all available frames are returned. The ordering of the returned list differs depending on whether a stack or a traceback is returned: the newest frames of a stack are returned, but the oldest frames of a traceback are returned. (This matches the behavior of the traceback module.)


print_stack(*, limit=None, file=None)
Print the stack or traceback for this Task. This produces output similar to that of the traceback module for the frames retrieved by get_stack(). The limit argument is passed to get_stack() directly. The file argument is an I/O stream to which the output is written; by default output is written to sys.stderr.


remove_done_callback(callback)
Remove callback from the callbacks list. This method should only be used in low-level callback-based code. See the documentation of Future.remove_done_callback() for more details.


result()
Return the result of the Task. If the Task is done, the result of the wrapped coroutine is returned (or if the coroutine raised an exception, that exception is re-raised.) If the Task has been cancelled, this method raises a CancelledError exception. If the Task’s result isn’t yet available, this method raises a InvalidStateError exception.


set_name(value)
Set the name of the Task. The value argument can be any object, which is then converted to a string. In the default Task implementation, the name will be visible in the repr() output of a task object.  New in version 3.8.


class asyncio.ThreadedChildWatcher
This implementation starts a new waiting thread for every subprocess spawn. It works reliably even when the asyncio event loop is run in a non-main OS thread. There is no noticeable overhead when handling a big number of children (O(1) each time a child terminates), but starting a thread per process requires extra memory. This watcher is used by default.  New in version 3.8.


exception asyncio.TimeoutError
The operation has exceeded the given deadline.  Important This exception is different from the builtin TimeoutError exception.


class asyncio.TimerHandle
A callback wrapper object returned by loop.call_later(), and loop.call_at(). This class is a subclass of Handle.
when()
Return a scheduled callback time as float seconds. The time is an absolute timestamp, using the same time reference as loop.time().  New in version 3.7.


when()
Return a scheduled callback time as float seconds. The time is an absolute timestamp, using the same time reference as loop.time().  New in version 3.7.


coroutine asyncio.to_thread(func, /, *args, **kwargs)
Asynchronously run function func in a separate thread. Any *args and **kwargs supplied for this function are directly passed to func. Also, the current contextvars.Context is propagated, allowing context variables from the event loop thread to be accessed in the separate thread. Return a coroutine that can be awaited to get the eventual result of func. This coroutine function is primarily intended to be used for executing IO-bound functions/methods that would otherwise block the event loop if they were ran in the main thread. For example: def blocking_io():
    print(f"start blocking_io at {time.strftime('%X')}")
    # Note that time.sleep() can be replaced with any blocking
    # IO-bound operation, such as file operations.
    time.sleep(1)
    print(f"blocking_io complete at {time.strftime('%X')}")

async def main():
    print(f"started main at {time.strftime('%X')}")

    await asyncio.gather(
        asyncio.to_thread(blocking_io),
        asyncio.sleep(1))

    print(f"finished main at {time.strftime('%X')}")

asyncio.run(main())

# Expected output:
#
# started main at 19:50:53
# start blocking_io at 19:50:53
# blocking_io complete at 19:50:54
# finished main at 19:50:54
 Directly calling blocking_io() in any coroutine would block the event loop for its duration, resulting in an additional 1 second of run time. Instead, by using asyncio.to_thread(), we can run it in a separate thread without blocking the event loop.  Note Due to the GIL, asyncio.to_thread() can typically only be used to make IO-bound functions non-blocking. However, for extension modules that release the GIL or alternative Python implementations that don’t have one, asyncio.to_thread() can also be used for CPU-bound functions.   New in version 3.9.


class asyncio.Transport(WriteTransport, ReadTransport)
Interface representing a bidirectional transport, such as a TCP connection. The user does not instantiate a transport directly; they call a utility function, passing it a protocol factory and other information necessary to create the transport and protocol. Instances of the Transport class are returned from or used by event loop methods like loop.create_connection(), loop.create_unix_connection(), loop.create_server(), loop.sendfile(), etc.


coroutine asyncio.wait(aws, *, loop=None, timeout=None, return_when=ALL_COMPLETED)
Run awaitable objects in the aws iterable concurrently and block until the condition specified by return_when. The aws iterable must not be empty. Returns two sets of Tasks/Futures: (done, pending). Usage: done, pending = await asyncio.wait(aws)
 timeout (a float or int), if specified, can be used to control the maximum number of seconds to wait before returning. Note that this function does not raise asyncio.TimeoutError. Futures or Tasks that aren’t done when the timeout occurs are simply returned in the second set. return_when indicates when this function should return. It must be one of the following constants:
Constant Description
FIRST_COMPLETED The function will return when any future finishes or is cancelled.
FIRST_EXCEPTION The function will return when any future finishes by raising an exception. If no future raises an exception then it is equivalent to ALL_COMPLETED.
ALL_COMPLETED The function will return when all futures finish or are cancelled.   Unlike wait_for(), wait() does not cancel the futures when a timeout occurs.  Deprecated since version 3.8: If any awaitable in aws is a coroutine, it is automatically scheduled as a Task. Passing coroutines objects to wait() directly is deprecated as it leads to confusing behavior.   Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.   Note wait() schedules coroutines as Tasks automatically and later returns those implicitly created Task objects in (done, pending) sets. Therefore the following code won’t work as expected: async def foo():
    return 42

coro = foo()
done, pending = await asyncio.wait({coro})

if coro in done:
    # This branch will never be run!
 Here is how the above snippet can be fixed: async def foo():
    return 42

task = asyncio.create_task(foo())
done, pending = await asyncio.wait({task})

if task in done:
    # Everything will work as expected now.
   Deprecated since version 3.8, will be removed in version 3.11: Passing coroutine objects to wait() directly is deprecated.


coroutine asyncio.wait_for(aw, timeout, *, loop=None)
Wait for the aw awaitable to complete with a timeout. If aw is a coroutine it is automatically scheduled as a Task. timeout can either be None or a float or int number of seconds to wait for. If timeout is None, block until the future completes. If a timeout occurs, it cancels the task and raises asyncio.TimeoutError. To avoid the task cancellation, wrap it in shield(). The function will wait until the future is actually cancelled, so the total wait time may exceed the timeout. If an exception happens during cancellation, it is propagated. If the wait is cancelled, the future aw is also cancelled.  Deprecated since version 3.8, will be removed in version 3.10: The loop parameter.  Example: async def eternity():
    # Sleep for one hour
    await asyncio.sleep(3600)
    print('yay!')

async def main():
    # Wait for at most 1 second
    try:
        await asyncio.wait_for(eternity(), timeout=1.0)
    except asyncio.TimeoutError:
        print('timeout!')

asyncio.run(main())

# Expected output:
#
#     timeout!
  Changed in version 3.7: When aw is cancelled due to a timeout, wait_for waits for aw to be cancelled. Previously, it raised asyncio.TimeoutError immediately.


class asyncio.WindowsProactorEventLoopPolicy
An alternative event loop policy that uses the ProactorEventLoop event loop implementation. Availability: Windows.


class asyncio.WindowsSelectorEventLoopPolicy
An alternative event loop policy that uses the SelectorEventLoop event loop implementation. Availability: Windows.


asyncio.wrap_future(future, *, loop=None)
Wrap a concurrent.futures.Future object in a asyncio.Future object.


class asyncio.WriteTransport(BaseTransport)
A base transport for write-only connections. Instances of the WriteTransport class are returned from the loop.connect_write_pipe() event loop method and are also used by subprocess-related methods like loop.subprocess_exec().


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


WriteTransport.can_write_eof()
Return True if the transport supports write_eof(), False if not.


WriteTransport.get_write_buffer_limits()
Get the high and low watermarks for write flow control. Return a tuple (low, high) where low and high are positive number of bytes. Use set_write_buffer_limits() to set the limits.  New in version 3.4.2.


WriteTransport.get_write_buffer_size()
Return the current size of the output buffer used by the transport.


WriteTransport.set_write_buffer_limits(high=None, low=None)
Set the high and low watermarks for write flow control. These two values (measured in number of bytes) control when the protocol’s protocol.pause_writing() and protocol.resume_writing() methods are called. If specified, the low watermark must be less than or equal to the high watermark. Neither high nor low can be negative. pause_writing() is called when the buffer size becomes greater than or equal to the high value. If writing has been paused, resume_writing() is called when the buffer size becomes less than or equal to the low value. The defaults are implementation-specific. If only the high watermark is given, the low watermark defaults to an implementation-specific value less than or equal to the high watermark. Setting high to zero forces low to zero as well, and causes pause_writing() to be called whenever the buffer becomes non-empty. Setting low to zero causes resume_writing() to be called only once the buffer is empty. Use of zero for either limit is generally sub-optimal as it reduces opportunities for doing I/O and computation concurrently. Use get_write_buffer_limits() to get the limits.


WriteTransport.write(data)
Write some data bytes to the transport. This method does not block; it buffers the data and arranges for it to be sent out asynchronously.


WriteTransport.writelines(list_of_data)
Write a list (or any iterable) of data bytes to the transport. This is functionally equivalent to calling write() on each element yielded by the iterable, but may be implemented more efficiently.


WriteTransport.write_eof()
Close the write end of the transport after flushing all buffered data. Data may still be received. This method can raise NotImplementedError if the transport (e.g. SSL) doesn’t support half-closed connections.


asyncore — Asynchronous socket handler Source code: Lib/asyncore.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 provides the basic infrastructure for writing asynchronous socket service clients and servers. There are only two ways to have a program on a single processor do “more than one thing at a time.” Multi-threaded programming is the simplest and most popular way to do it, but there is another very different technique, that lets you have nearly all the advantages of multi-threading, without actually using multiple threads. It’s really only practical if your program is largely I/O bound. If your program is processor bound, then pre-emptive scheduled threads are probably what you really need. Network servers are rarely processor bound, however. If your operating system supports the select() system call in its I/O library (and nearly all do), then you can use it to juggle multiple communication channels at once; doing other work while your I/O is taking place in the “background.” Although this strategy can seem strange and complex, especially at first, it is in many ways easier to understand and control than multi-threaded programming. The asyncore module solves many of the difficult problems for you, making the task of building sophisticated high-performance network servers and clients a snap. For “conversational” applications and protocols the companion asynchat module is invaluable. The basic idea behind both modules is to create one or more network channels, instances of class asyncore.dispatcher and asynchat.async_chat. Creating the channels adds them to a global map, used by the loop() function if you do not provide it with your own map. Once the initial channel(s) is(are) created, calling the loop() function activates channel service, which continues until the last channel (including any that have been added to the map during asynchronous service) is closed.
asyncore.loop([timeout[, use_poll[, map[, count]]]])
Enter a polling loop that terminates after count passes or all open channels have been closed. All arguments are optional. The count parameter defaults to None, resulting in the loop terminating only when all channels have been closed. The timeout argument sets the timeout parameter for the appropriate select() or poll() call, measured in seconds; the default is 30 seconds. The use_poll parameter, if true, indicates that poll() should be used in preference to select() (the default is False). The map parameter is a dictionary whose items are the channels to watch. As channels are closed they are deleted from their map. If map is omitted, a global map is used. Channels (instances of asyncore.dispatcher, asynchat.async_chat and subclasses thereof) can freely be mixed in the map.

class asyncore.dispatcher
The dispatcher class is a thin wrapper around a low-level socket object. To make it more useful, it has a few methods for event-handling which are called from the asynchronous loop. Otherwise, it can be treated as a normal non-blocking socket object. The firing of low-level events at certain times or in certain connection states tells the asynchronous loop that certain higher-level events have taken place. For example, if we have asked for a socket to connect to another host, we know that the connection has been made when the socket becomes writable for the first time (at this point you know that you may write to it with the expectation of success). The implied higher-level events are:
Event Description
handle_connect() Implied by the first read or write event
handle_close() Implied by a read event with no data available
handle_accepted() Implied by a read event on a listening socket   During asynchronous processing, each mapped channel’s readable() and writable() methods are used to determine whether the channel’s socket should be added to the list of channels select()ed or poll()ed for read and write events. Thus, the set of channel events is larger than the basic socket events. The full set of methods that can be overridden in your subclass follows:
handle_read()
Called when the asynchronous loop detects that a read() call on the channel’s socket will succeed.

handle_write()
Called when the asynchronous loop detects that a writable socket can be written. Often this method will implement the necessary buffering for performance. For example: def handle_write(self):
    sent = self.send(self.buffer)
    self.buffer = self.buffer[sent:]

handle_expt()
Called when there is out of band (OOB) data for a socket connection. This will almost never happen, as OOB is tenuously supported and rarely used.

handle_connect()
Called when the active opener’s socket actually makes a connection. Might send a “welcome” banner, or initiate a protocol negotiation with the remote endpoint, for example.

handle_close()
Called when the socket is closed.

handle_error()
Called when an exception is raised and not otherwise handled. The default version prints a condensed traceback.

handle_accept()
Called on listening channels (passive openers) when a connection can be established with a new remote endpoint that has issued a connect() call for the local endpoint. Deprecated in version 3.2; use handle_accepted() instead.  Deprecated since version 3.2.

handle_accepted(sock, addr)
Called on listening channels (passive openers) when a connection has been established with a new remote endpoint that has issued a connect() call for the local endpoint. sock is a new socket object usable to send and receive data on the connection, and addr is the address bound to the socket on the other end of the connection.  New in version 3.2.

readable()
Called each time around the asynchronous loop to determine whether a channel’s socket should be added to the list on which read events can occur. The default method simply returns True, indicating that by default, all channels will be interested in read events.

writable()
Called each time around the asynchronous loop to determine whether a channel’s socket should be added to the list on which write events can occur. The default method simply returns True, indicating that by default, all channels will be interested in write events.
 In addition, each channel delegates or extends many of the socket methods. Most of these are nearly identical to their socket partners.
create_socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
This is identical to the creation of a normal socket, and will use the same options for creation. Refer to the socket documentation for information on creating sockets.  Changed in version 3.3: family and type arguments can be omitted.

connect(address)
As with the normal socket object, address is a tuple with the first element the host to connect to, and the second the port number.

send(data)
Send data to the remote end-point of the socket.

recv(buffer_size)
Read at most buffer_size bytes from the socket’s remote end-point. An empty bytes object implies that the channel has been closed from the other end. Note that recv() may raise BlockingIOError , even though select.select() or select.poll() has reported the socket ready for reading.

listen(backlog)
Listen for connections made to the socket. The backlog argument specifies the maximum number of queued connections and should be at least 1; the maximum value is system-dependent (usually 5).

bind(address)
Bind the socket to address. The socket must not already be bound. (The format of address depends on the address family — refer to the socket documentation for more information.) To mark the socket as re-usable (setting the SO_REUSEADDR option), call the dispatcher object’s set_reuse_addr() method.

accept()
Accept a connection. The socket must be bound to an address and listening for connections. The return value can be either None or 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. When None is returned it means the connection didn’t take place, in which case the server should just ignore this event and keep listening for further incoming connections.

close()
Close the socket. All future operations on the socket object will fail. The remote end-point will receive no more data (after queued data is flushed). Sockets are automatically closed when they are garbage-collected.

class asyncore.dispatcher_with_send
A dispatcher subclass which adds simple buffered output capability, useful for simple clients. For more sophisticated usage use asynchat.async_chat.

class asyncore.file_dispatcher
A file_dispatcher takes a file descriptor or file object along with an optional map argument and wraps it for use with the poll() or loop() functions. If provided a file object or anything with a fileno() method, that method will be called and passed to the file_wrapper constructor. Availability: Unix.

class asyncore.file_wrapper
A file_wrapper takes an integer file descriptor and calls os.dup() to duplicate the handle so that the original handle may be closed independently of the file_wrapper. This class implements sufficient methods to emulate a socket for use by the file_dispatcher class. Availability: Unix.
 asyncore Example basic HTTP client Here is a very basic HTTP client that uses the dispatcher class to implement its socket handling: import asyncore

class HTTPClient(asyncore.dispatcher):

    def __init__(self, host, path):
        asyncore.dispatcher.__init__(self)
        self.create_socket()
        self.connect( (host, 80) )
        self.buffer = bytes('GET %s HTTP/1.0\r\nHost: %s\r\n\r\n' %
                            (path, host), 'ascii')

    def handle_connect(self):
        pass

    def handle_close(self):
        self.close()

    def handle_read(self):
        print(self.recv(8192))

    def writable(self):
        return (len(self.buffer) > 0)

    def handle_write(self):
        sent = self.send(self.buffer)
        self.buffer = self.buffer[sent:]

client = HTTPClient('www.python.org', '/')
asyncore.loop()
 asyncore Example basic echo server Here is a basic echo server that uses the dispatcher class to accept connections and dispatches the incoming connections to a handler: import asyncore

class EchoHandler(asyncore.dispatcher_with_send):

    def handle_read(self):
        data = self.recv(8192)
        if data:
            self.send(data)

class EchoServer(asyncore.dispatcher):

    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket()
        self.set_reuse_addr()
        self.bind((host, port))
        self.listen(5)

    def handle_accepted(self, sock, addr):
        print('Incoming connection from %s' % repr(addr))
        handler = EchoHandler(sock)

server = EchoServer('localhost', 8080)
asyncore.loop()


class asyncore.dispatcher
The dispatcher class is a thin wrapper around a low-level socket object. To make it more useful, it has a few methods for event-handling which are called from the asynchronous loop. Otherwise, it can be treated as a normal non-blocking socket object. The firing of low-level events at certain times or in certain connection states tells the asynchronous loop that certain higher-level events have taken place. For example, if we have asked for a socket to connect to another host, we know that the connection has been made when the socket becomes writable for the first time (at this point you know that you may write to it with the expectation of success). The implied higher-level events are:
Event Description
handle_connect() Implied by the first read or write event
handle_close() Implied by a read event with no data available
handle_accepted() Implied by a read event on a listening socket   During asynchronous processing, each mapped channel’s readable() and writable() methods are used to determine whether the channel’s socket should be added to the list of channels select()ed or poll()ed for read and write events. Thus, the set of channel events is larger than the basic socket events. The full set of methods that can be overridden in your subclass follows:
handle_read()
Called when the asynchronous loop detects that a read() call on the channel’s socket will succeed.

handle_write()
Called when the asynchronous loop detects that a writable socket can be written. Often this method will implement the necessary buffering for performance. For example: def handle_write(self):
    sent = self.send(self.buffer)
    self.buffer = self.buffer[sent:]

handle_expt()
Called when there is out of band (OOB) data for a socket connection. This will almost never happen, as OOB is tenuously supported and rarely used.

handle_connect()
Called when the active opener’s socket actually makes a connection. Might send a “welcome” banner, or initiate a protocol negotiation with the remote endpoint, for example.

handle_close()
Called when the socket is closed.

handle_error()
Called when an exception is raised and not otherwise handled. The default version prints a condensed traceback.

handle_accept()
Called on listening channels (passive openers) when a connection can be established with a new remote endpoint that has issued a connect() call for the local endpoint. Deprecated in version 3.2; use handle_accepted() instead.  Deprecated since version 3.2.

handle_accepted(sock, addr)
Called on listening channels (passive openers) when a connection has been established with a new remote endpoint that has issued a connect() call for the local endpoint. sock is a new socket object usable to send and receive data on the connection, and addr is the address bound to the socket on the other end of the connection.  New in version 3.2.

readable()
Called each time around the asynchronous loop to determine whether a channel’s socket should be added to the list on which read events can occur. The default method simply returns True, indicating that by default, all channels will be interested in read events.

writable()
Called each time around the asynchronous loop to determine whether a channel’s socket should be added to the list on which write events can occur. The default method simply returns True, indicating that by default, all channels will be interested in write events.
 In addition, each channel delegates or extends many of the socket methods. Most of these are nearly identical to their socket partners.
create_socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
This is identical to the creation of a normal socket, and will use the same options for creation. Refer to the socket documentation for information on creating sockets.  Changed in version 3.3: family and type arguments can be omitted.

connect(address)
As with the normal socket object, address is a tuple with the first element the host to connect to, and the second the port number.

send(data)
Send data to the remote end-point of the socket.

recv(buffer_size)
Read at most buffer_size bytes from the socket’s remote end-point. An empty bytes object implies that the channel has been closed from the other end. Note that recv() may raise BlockingIOError , even though select.select() or select.poll() has reported the socket ready for reading.

listen(backlog)
Listen for connections made to the socket. The backlog argument specifies the maximum number of queued connections and should be at least 1; the maximum value is system-dependent (usually 5).

bind(address)
Bind the socket to address. The socket must not already be bound. (The format of address depends on the address family — refer to the socket documentation for more information.) To mark the socket as re-usable (setting the SO_REUSEADDR option), call the dispatcher object’s set_reuse_addr() method.

accept()
Accept a connection. The socket must be bound to an address and listening for connections. The return value can be either None or 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. When None is returned it means the connection didn’t take place, in which case the server should just ignore this event and keep listening for further incoming connections.

close()
Close the socket. All future operations on the socket object will fail. The remote end-point will receive no more data (after queued data is flushed). Sockets are automatically closed when they are garbage-collected.


accept()
Accept a connection. The socket must be bound to an address and listening for connections. The return value can be either None or 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. When None is returned it means the connection didn’t take place, in which case the server should just ignore this event and keep listening for further incoming connections.


bind(address)
Bind the socket to address. The socket must not already be bound. (The format of address depends on the address family — refer to the socket documentation for more information.) To mark the socket as re-usable (setting the SO_REUSEADDR option), call the dispatcher object’s set_reuse_addr() method.


close()
Close the socket. All future operations on the socket object will fail. The remote end-point will receive no more data (after queued data is flushed). Sockets are automatically closed when they are garbage-collected.


connect(address)
As with the normal socket object, address is a tuple with the first element the host to connect to, and the second the port number.


create_socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
This is identical to the creation of a normal socket, and will use the same options for creation. Refer to the socket documentation for information on creating sockets.  Changed in version 3.3: family and type arguments can be omitted.


handle_accept()
Called on listening channels (passive openers) when a connection can be established with a new remote endpoint that has issued a connect() call for the local endpoint. Deprecated in version 3.2; use handle_accepted() instead.  Deprecated since version 3.2.


handle_accepted(sock, addr)
Called on listening channels (passive openers) when a connection has been established with a new remote endpoint that has issued a connect() call for the local endpoint. sock is a new socket object usable to send and receive data on the connection, and addr is the address bound to the socket on the other end of the connection.  New in version 3.2.


handle_close()
Called when the socket is closed.


handle_connect()
Called when the active opener’s socket actually makes a connection. Might send a “welcome” banner, or initiate a protocol negotiation with the remote endpoint, for example.


handle_error()
Called when an exception is raised and not otherwise handled. The default version prints a condensed traceback.


handle_expt()
Called when there is out of band (OOB) data for a socket connection. This will almost never happen, as OOB is tenuously supported and rarely used.


handle_read()
Called when the asynchronous loop detects that a read() call on the channel’s socket will succeed.


handle_write()
Called when the asynchronous loop detects that a writable socket can be written. Often this method will implement the necessary buffering for performance. For example: def handle_write(self):
    sent = self.send(self.buffer)
    self.buffer = self.buffer[sent:]


listen(backlog)
Listen for connections made to the socket. The backlog argument specifies the maximum number of queued connections and should be at least 1; the maximum value is system-dependent (usually 5).


readable()
Called each time around the asynchronous loop to determine whether a channel’s socket should be added to the list on which read events can occur. The default method simply returns True, indicating that by default, all channels will be interested in read events.


recv(buffer_size)
Read at most buffer_size bytes from the socket’s remote end-point. An empty bytes object implies that the channel has been closed from the other end. Note that recv() may raise BlockingIOError , even though select.select() or select.poll() has reported the socket ready for reading.


send(data)
Send data to the remote end-point of the socket.


writable()
Called each time around the asynchronous loop to determine whether a channel’s socket should be added to the list on which write events can occur. The default method simply returns True, indicating that by default, all channels will be interested in write events.


class asyncore.dispatcher_with_send
A dispatcher subclass which adds simple buffered output capability, useful for simple clients. For more sophisticated usage use asynchat.async_chat.


class asyncore.file_dispatcher
A file_dispatcher takes a file descriptor or file object along with an optional map argument and wraps it for use with the poll() or loop() functions. If provided a file object or anything with a fileno() method, that method will be called and passed to the file_wrapper constructor. Availability: Unix.


class asyncore.file_wrapper
A file_wrapper takes an integer file descriptor and calls os.dup() to duplicate the handle so that the original handle may be closed independently of the file_wrapper. This class implements sufficient methods to emulate a socket for use by the file_dispatcher class. Availability: Unix.


asyncore.loop([timeout[, use_poll[, map[, count]]]])
Enter a polling loop that terminates after count passes or all open channels have been closed. All arguments are optional. The count parameter defaults to None, resulting in the loop terminating only when all channels have been closed. The timeout argument sets the timeout parameter for the appropriate select() or poll() call, measured in seconds; the default is 30 seconds. The use_poll parameter, if true, indicates that poll() should be used in preference to select() (the default is False). The map parameter is a dictionary whose items are the channels to watch. As channels are closed they are deleted from their map. If map is omitted, a global map is used. Channels (instances of asyncore.dispatcher, asynchat.async_chat and subclasses thereof) can freely be mixed in the map.


atexit — Exit handlers The atexit module defines functions to register and unregister cleanup functions. Functions thus registered are automatically executed upon normal interpreter termination. atexit runs these functions in the reverse order in which they were registered; if you register A, B, and C, at interpreter termination time they will be run in the order C, B, A. Note: The functions registered via this module are not called when the program is killed by a signal not handled by Python, when a Python fatal internal error is detected, or when os._exit() is called.  Changed in version 3.7: When used with C-API subinterpreters, registered functions are local to the interpreter they were registered in.
atexit.register(func, *args, **kwargs)
Register func as a function to be executed at termination. Any optional arguments that are to be passed to func must be passed as arguments to register(). It is possible to register the same function and arguments more than once. At normal program termination (for instance, if sys.exit() is called or the main module’s execution completes), all functions registered are called in last in, first out order. The assumption is that lower level modules will normally be imported before higher level modules and thus must be cleaned up later. If an exception is raised during execution of the exit handlers, a traceback is printed (unless SystemExit is raised) and the exception information is saved. After all exit handlers have had a chance to run the last exception to be raised is re-raised. This function returns func, which makes it possible to use it as a decorator.

atexit.unregister(func)
Remove func from the list of functions to be run at interpreter shutdown. After calling unregister(), func is guaranteed not to be called when the interpreter shuts down, even if it was registered more than once. unregister() silently does nothing if func was not previously registered.
  See also
Module readline

Useful example of atexit to read and write readline history files.    atexit Example The following simple example demonstrates how a module can initialize a counter from a file when it is imported and save the counter’s updated value automatically when the program terminates without relying on the application making an explicit call into this module at termination. try:
    with open("counterfile") as infile:
        _count = int(infile.read())
except FileNotFoundError:
    _count = 0

def incrcounter(n):
    global _count
    _count = _count + n

def savecounter():
    with open("counterfile", "w") as outfile:
        outfile.write("%d" % _count)

import atexit
atexit.register(savecounter)
 Positional and keyword arguments may also be passed to register() to be passed along to the registered function when it is called: def goodbye(name, adjective):
    print('Goodbye, %s, it was %s to meet you.' % (name, adjective))

import atexit
atexit.register(goodbye, 'Donny', 'nice')

# or:
atexit.register(goodbye, adjective='nice', name='Donny')
 Usage as a decorator: import atexit

@atexit.register
def goodbye():
    print("You are now leaving the Python sector.")
 This only works with functions that can be called without arguments.


atexit.register(func, *args, **kwargs)
Register func as a function to be executed at termination. Any optional arguments that are to be passed to func must be passed as arguments to register(). It is possible to register the same function and arguments more than once. At normal program termination (for instance, if sys.exit() is called or the main module’s execution completes), all functions registered are called in last in, first out order. The assumption is that lower level modules will normally be imported before higher level modules and thus must be cleaned up later. If an exception is raised during execution of the exit handlers, a traceback is printed (unless SystemExit is raised) and the exception information is saved. After all exit handlers have had a chance to run the last exception to be raised is re-raised. This function returns func, which makes it possible to use it as a decorator.


atexit.unregister(func)
Remove func from the list of functions to be run at interpreter shutdown. After calling unregister(), func is guaranteed not to be called when the interpreter shuts down, even if it was registered more than once. unregister() silently does nothing if func was not previously registered.


exception AttributeError
Raised when an attribute reference (see Attribute references) or assignment fails. (When an object does not support attribute references or attribute assignments at all, TypeError is raised.)


audioop — Manipulate raw audio data The audioop module contains some useful operations on sound fragments. It operates on sound fragments consisting of signed integer samples 8, 16, 24 or 32 bits wide, stored in bytes-like objects. All scalar items are integers, unless specified otherwise.  Changed in version 3.4: Support for 24-bit samples was added. All functions now accept any bytes-like object. String input now results in an immediate error.  This module provides support for a-LAW, u-LAW and Intel/DVI ADPCM encodings. A few of the more complicated operations only take 16-bit samples, otherwise the sample size (in bytes) is always a parameter of the operation. The module defines the following variables and functions:
exception audioop.error
This exception is raised on all errors, such as unknown number of bytes per sample, etc.

audioop.add(fragment1, fragment2, width)
Return a fragment which is the addition of the two samples passed as parameters. width is the sample width in bytes, either 1, 2, 3 or 4. Both fragments should have the same length. Samples are truncated in case of overflow.

audioop.adpcm2lin(adpcmfragment, width, state)
Decode an Intel/DVI ADPCM coded fragment to a linear fragment. See the description of lin2adpcm() for details on ADPCM coding. Return a tuple (sample, newstate) where the sample has the width specified in width.

audioop.alaw2lin(fragment, width)
Convert sound fragments in a-LAW encoding to linearly encoded sound fragments. a-LAW encoding always uses 8 bits samples, so width refers only to the sample width of the output fragment here.

audioop.avg(fragment, width)
Return the average over all samples in the fragment.

audioop.avgpp(fragment, width)
Return the average peak-peak value over all samples in the fragment. No filtering is done, so the usefulness of this routine is questionable.

audioop.bias(fragment, width, bias)
Return a fragment that is the original fragment with a bias added to each sample. Samples wrap around in case of overflow.

audioop.byteswap(fragment, width)
“Byteswap” all samples in a fragment and returns the modified fragment. Converts big-endian samples to little-endian and vice versa.  New in version 3.4.

audioop.cross(fragment, width)
Return the number of zero crossings in the fragment passed as an argument.

audioop.findfactor(fragment, reference)
Return a factor F such that rms(add(fragment, mul(reference, -F))) is minimal, i.e., return the factor with which you should multiply reference to make it match as well as possible to fragment. The fragments should both contain 2-byte samples. The time taken by this routine is proportional to len(fragment).

audioop.findfit(fragment, reference)
Try to match reference as well as possible to a portion of fragment (which should be the longer fragment). This is (conceptually) done by taking slices out of fragment, using findfactor() to compute the best match, and minimizing the result. The fragments should both contain 2-byte samples. Return a tuple (offset, factor) where offset is the (integer) offset into fragment where the optimal match started and factor is the (floating-point) factor as per findfactor().

audioop.findmax(fragment, length)
Search fragment for a slice of length length samples (not bytes!) with maximum energy, i.e., return i for which rms(fragment[i*2:(i+length)*2]) is maximal. The fragments should both contain 2-byte samples. The routine takes time proportional to len(fragment).

audioop.getsample(fragment, width, index)
Return the value of sample index from the fragment.

audioop.lin2adpcm(fragment, width, state)
Convert samples to 4 bit Intel/DVI ADPCM encoding. ADPCM coding is an adaptive coding scheme, whereby each 4 bit number is the difference between one sample and the next, divided by a (varying) step. The Intel/DVI ADPCM algorithm has been selected for use by the IMA, so it may well become a standard. state is a tuple containing the state of the coder. The coder returns a tuple (adpcmfrag, newstate), and the newstate should be passed to the next call of lin2adpcm(). In the initial call, None can be passed as the state. adpcmfrag is the ADPCM coded fragment packed 2 4-bit values per byte.

audioop.lin2alaw(fragment, width)
Convert samples in the audio fragment to a-LAW encoding and return this as a bytes object. a-LAW is an audio encoding format whereby you get a dynamic range of about 13 bits using only 8 bit samples. It is used by the Sun audio hardware, among others.

audioop.lin2lin(fragment, width, newwidth)
Convert samples between 1-, 2-, 3- and 4-byte formats.  Note In some audio formats, such as .WAV files, 16, 24 and 32 bit samples are signed, but 8 bit samples are unsigned. So when converting to 8 bit wide samples for these formats, you need to also add 128 to the result: new_frames = audioop.lin2lin(frames, old_width, 1)
new_frames = audioop.bias(new_frames, 1, 128)
 The same, in reverse, has to be applied when converting from 8 to 16, 24 or 32 bit width samples.

audioop.lin2ulaw(fragment, width)
Convert samples in the audio fragment to u-LAW encoding and return this as a bytes object. u-LAW is an audio encoding format whereby you get a dynamic range of about 14 bits using only 8 bit samples. It is used by the Sun audio hardware, among others.

audioop.max(fragment, width)
Return the maximum of the absolute value of all samples in a fragment.

audioop.maxpp(fragment, width)
Return the maximum peak-peak value in the sound fragment.

audioop.minmax(fragment, width)
Return a tuple consisting of the minimum and maximum values of all samples in the sound fragment.

audioop.mul(fragment, width, factor)
Return a fragment that has all samples in the original fragment multiplied by the floating-point value factor. Samples are truncated in case of overflow.

audioop.ratecv(fragment, width, nchannels, inrate, outrate, state[, weightA[, weightB]])
Convert the frame rate of the input fragment. state is a tuple containing the state of the converter. The converter returns a tuple (newfragment, newstate), and newstate should be passed to the next call of ratecv(). The initial call should pass None as the state. The weightA and weightB arguments are parameters for a simple digital filter and default to 1 and 0 respectively.

audioop.reverse(fragment, width)
Reverse the samples in a fragment and returns the modified fragment.

audioop.rms(fragment, width)
Return the root-mean-square of the fragment, i.e. sqrt(sum(S_i^2)/n). This is a measure of the power in an audio signal.

audioop.tomono(fragment, width, lfactor, rfactor)
Convert a stereo fragment to a mono fragment. The left channel is multiplied by lfactor and the right channel by rfactor before adding the two channels to give a mono signal.

audioop.tostereo(fragment, width, lfactor, rfactor)
Generate a stereo fragment from a mono fragment. Each pair of samples in the stereo fragment are computed from the mono sample, whereby left channel samples are multiplied by lfactor and right channel samples by rfactor.

audioop.ulaw2lin(fragment, width)
Convert sound fragments in u-LAW encoding to linearly encoded sound fragments. u-LAW encoding always uses 8 bits samples, so width refers only to the sample width of the output fragment here.
 Note that operations such as mul() or max() make no distinction between mono and stereo fragments, i.e. all samples are treated equal. If this is a problem the stereo fragment should be split into two mono fragments first and recombined later. Here is an example of how to do that: def mul_stereo(sample, width, lfactor, rfactor):
    lsample = audioop.tomono(sample, width, 1, 0)
    rsample = audioop.tomono(sample, width, 0, 1)
    lsample = audioop.mul(lsample, width, lfactor)
    rsample = audioop.mul(rsample, width, rfactor)
    lsample = audioop.tostereo(lsample, width, 1, 0)
    rsample = audioop.tostereo(rsample, width, 0, 1)
    return audioop.add(lsample, rsample, width)
 If you use the ADPCM coder to build network packets and you want your protocol to be stateless (i.e. to be able to tolerate packet loss) you should not only transmit the data but also the state. Note that you should send the initial state (the one you passed to lin2adpcm()) along to the decoder, not the final state (as returned by the coder). If you want to use struct.Struct to store the state in binary you can code the first element (the predicted value) in 16 bits and the second (the delta index) in 8. The ADPCM coders have never been tried against other ADPCM coders, only against themselves. It could well be that I misinterpreted the standards in which case they will not be interoperable with the respective standards. The find*() routines might look a bit funny at first sight. They are primarily meant to do echo cancellation. A reasonably fast way to do this is to pick the most energetic piece of the output sample, locate that in the input sample and subtract the whole output sample from the input sample: def echocancel(outputdata, inputdata):
    pos = audioop.findmax(outputdata, 800)    # one tenth second
    out_test = outputdata[pos*2:]
    in_test = inputdata[pos*2:]
    ipos, factor = audioop.findfit(in_test, out_test)
    # Optional (for better cancellation):
    # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],
    #              out_test)
    prefill = '\0'*(pos+ipos)*2
    postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata))
    outputdata = prefill + audioop.mul(outputdata, 2, -factor) + postfill
    return audioop.add(inputdata, outputdata, 2)


audioop.add(fragment1, fragment2, width)
Return a fragment which is the addition of the two samples passed as parameters. width is the sample width in bytes, either 1, 2, 3 or 4. Both fragments should have the same length. Samples are truncated in case of overflow.


audioop.adpcm2lin(adpcmfragment, width, state)
Decode an Intel/DVI ADPCM coded fragment to a linear fragment. See the description of lin2adpcm() for details on ADPCM coding. Return a tuple (sample, newstate) where the sample has the width specified in width.


audioop.alaw2lin(fragment, width)
Convert sound fragments in a-LAW encoding to linearly encoded sound fragments. a-LAW encoding always uses 8 bits samples, so width refers only to the sample width of the output fragment here.


audioop.avg(fragment, width)
Return the average over all samples in the fragment.


audioop.avgpp(fragment, width)
Return the average peak-peak value over all samples in the fragment. No filtering is done, so the usefulness of this routine is questionable.


audioop.bias(fragment, width, bias)
Return a fragment that is the original fragment with a bias added to each sample. Samples wrap around in case of overflow.


audioop.byteswap(fragment, width)
“Byteswap” all samples in a fragment and returns the modified fragment. Converts big-endian samples to little-endian and vice versa.  New in version 3.4.


audioop.cross(fragment, width)
Return the number of zero crossings in the fragment passed as an argument.


exception audioop.error
This exception is raised on all errors, such as unknown number of bytes per sample, etc.


audioop.findfactor(fragment, reference)
Return a factor F such that rms(add(fragment, mul(reference, -F))) is minimal, i.e., return the factor with which you should multiply reference to make it match as well as possible to fragment. The fragments should both contain 2-byte samples. The time taken by this routine is proportional to len(fragment).


audioop.findfit(fragment, reference)
Try to match reference as well as possible to a portion of fragment (which should be the longer fragment). This is (conceptually) done by taking slices out of fragment, using findfactor() to compute the best match, and minimizing the result. The fragments should both contain 2-byte samples. Return a tuple (offset, factor) where offset is the (integer) offset into fragment where the optimal match started and factor is the (floating-point) factor as per findfactor().


audioop.findmax(fragment, length)
Search fragment for a slice of length length samples (not bytes!) with maximum energy, i.e., return i for which rms(fragment[i*2:(i+length)*2]) is maximal. The fragments should both contain 2-byte samples. The routine takes time proportional to len(fragment).


audioop.getsample(fragment, width, index)
Return the value of sample index from the fragment.


audioop.lin2adpcm(fragment, width, state)
Convert samples to 4 bit Intel/DVI ADPCM encoding. ADPCM coding is an adaptive coding scheme, whereby each 4 bit number is the difference between one sample and the next, divided by a (varying) step. The Intel/DVI ADPCM algorithm has been selected for use by the IMA, so it may well become a standard. state is a tuple containing the state of the coder. The coder returns a tuple (adpcmfrag, newstate), and the newstate should be passed to the next call of lin2adpcm(). In the initial call, None can be passed as the state. adpcmfrag is the ADPCM coded fragment packed 2 4-bit values per byte.


audioop.lin2alaw(fragment, width)
Convert samples in the audio fragment to a-LAW encoding and return this as a bytes object. a-LAW is an audio encoding format whereby you get a dynamic range of about 13 bits using only 8 bit samples. It is used by the Sun audio hardware, among others.


audioop.lin2lin(fragment, width, newwidth)
Convert samples between 1-, 2-, 3- and 4-byte formats.  Note In some audio formats, such as .WAV files, 16, 24 and 32 bit samples are signed, but 8 bit samples are unsigned. So when converting to 8 bit wide samples for these formats, you need to also add 128 to the result: new_frames = audioop.lin2lin(frames, old_width, 1)
new_frames = audioop.bias(new_frames, 1, 128)
 The same, in reverse, has to be applied when converting from 8 to 16, 24 or 32 bit width samples.


audioop.lin2ulaw(fragment, width)
Convert samples in the audio fragment to u-LAW encoding and return this as a bytes object. u-LAW is an audio encoding format whereby you get a dynamic range of about 14 bits using only 8 bit samples. It is used by the Sun audio hardware, among others.


audioop.max(fragment, width)
Return the maximum of the absolute value of all samples in a fragment.


audioop.maxpp(fragment, width)
Return the maximum peak-peak value in the sound fragment.


audioop.minmax(fragment, width)
Return a tuple consisting of the minimum and maximum values of all samples in the sound fragment.


audioop.mul(fragment, width, factor)
Return a fragment that has all samples in the original fragment multiplied by the floating-point value factor. Samples are truncated in case of overflow.


audioop.ratecv(fragment, width, nchannels, inrate, outrate, state[, weightA[, weightB]])
Convert the frame rate of the input fragment. state is a tuple containing the state of the converter. The converter returns a tuple (newfragment, newstate), and newstate should be passed to the next call of ratecv(). The initial call should pass None as the state. The weightA and weightB arguments are parameters for a simple digital filter and default to 1 and 0 respectively.


audioop.reverse(fragment, width)
Reverse the samples in a fragment and returns the modified fragment.


audioop.rms(fragment, width)
Return the root-mean-square of the fragment, i.e. sqrt(sum(S_i^2)/n). This is a measure of the power in an audio signal.


audioop.tomono(fragment, width, lfactor, rfactor)
Convert a stereo fragment to a mono fragment. The left channel is multiplied by lfactor and the right channel by rfactor before adding the two channels to give a mono signal.


audioop.tostereo(fragment, width, lfactor, rfactor)
Generate a stereo fragment from a mono fragment. Each pair of samples in the stereo fragment are computed from the mono sample, whereby left channel samples are multiplied by lfactor and right channel samples by rfactor.


audioop.ulaw2lin(fragment, width)
Convert sound fragments in u-LAW encoding to linearly encoded sound fragments. u-LAW encoding always uses 8 bits samples, so width refers only to the sample width of the output fragment here.