API 参考

API reference

事件循环

Event loop

anyio.run(func, *args, backend='asyncio', backend_options=None)

Run the given coroutine function in an asynchronous event loop.

The current thread must not be already running an event loop.

参数:
  • func (Callable[[Unpack[TypeVarTuple]], Awaitable[TypeVar(T_Retval)]]) -- a coroutine function

  • args (Unpack[TypeVarTuple]) -- positional arguments to func

  • backend (str) -- name of the asynchronous event loop implementation – currently either asyncio or trio

  • backend_options (dict[str, Any] | None) -- keyword arguments to call the backend run() implementation with (documented here)

返回类型:

TypeVar(T_Retval)

返回:

the return value of the coroutine function

抛出:
  • RuntimeError -- if an asynchronous event loop is already running in this thread

  • LookupError -- if the named backend is not found

anyio.get_all_backends()

Return a tuple of the names of all built-in backends.

返回类型:

tuple[str, ...]

anyio.get_cancelled_exc_class()

Return the current async library's cancellation exception class.

返回类型:

type[BaseException]

async anyio.sleep(delay)

Pause the current task for the specified duration.

参数:

delay (float) -- the duration, in seconds

返回类型:

None

async anyio.sleep_forever()

Pause the current task until it's cancelled.

This is a shortcut for sleep(math.inf). :rtype: None

Added in version 3.1.

async anyio.sleep_until(deadline)

Pause the current task until the given time.

参数:

deadline (float) -- the absolute time to wake up at (according to the internal monotonic clock of the event loop)

返回类型:

None

Added in version 3.1.

anyio.current_time()

Return the current value of the event loop's internal clock.

返回类型:

float

返回:

the clock value (seconds)

异步资源

Asynchronous resources

async anyio.aclose_forcefully(resource)

Close an asynchronous resource in a cancelled scope.

Doing this closes the resource without waiting on anything.

参数:

resource (AsyncResource) -- the resource to close

返回类型:

None

class anyio.abc.AsyncResource

基类:object

Abstract base class for all closeable asynchronous resources.

Works as an asynchronous context manager which returns the instance itself on enter, and calls aclose() on exit.

abstract async aclose()

Close the resource.

返回类型:

None

类型化属性

Typed attributes

anyio.typed_attribute()

Return a unique object, used to mark typed attributes.

返回类型:

Any

class anyio.TypedAttributeSet

基类:object

Superclass for typed attribute collections.

Checks that every public attribute of every subclass has a type annotation.

class anyio.TypedAttributeProvider

基类:object

Base class for classes that wish to provide typed extra attributes.

extra(attribute, default=<object object>)

Return the value of the given typed extra attribute.

参数:
  • attribute (Any) -- the attribute (member of a TypedAttributeSet) to look for

  • default (object) -- the value that should be returned if no value is found for the attribute

抛出:

TypedAttributeLookupError -- if the search failed and no default value was given

返回类型:

object

property extra_attributes: Mapping[T_Attr, Callable[[], T_Attr]]

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

超时和取消

Timeouts and cancellation

anyio.move_on_after(delay, shield=False)

Create a cancel scope with a deadline that expires after the given delay.

参数:
  • delay (float | None) -- maximum allowed time (in seconds) before exiting the context block, or None to disable the timeout

  • shield (bool) -- True to shield the cancel scope from external cancellation

返回类型:

CancelScope

返回:

a cancel scope

anyio.fail_after(delay, shield=False)

Create a context manager which raises a TimeoutError if does not finish in time.

参数:
  • delay (float | None) -- maximum allowed time (in seconds) before raising the exception, or None to disable the timeout

  • shield (bool) -- True to shield the cancel scope from external cancellation

返回:

a context manager that yields a cancel scope

返回类型:

ContextManager[CancelScope]

anyio.current_effective_deadline()

Return the nearest deadline among all the cancel scopes effective for the current task.

返回:

a clock value from the event loop's internal clock (or float('inf') if there is no deadline in effect, or float('-inf') if the current scope has been cancelled)

返回类型:

float

class anyio.CancelScope(*, deadline: float = inf, shield: bool = False)

基类:object

Wraps a unit of work that can be made separately cancellable.

参数:
  • deadline -- The time (clock value) when this scope is cancelled automatically

  • shield -- True to shield the cancel scope from external cancellation

cancel()

Cancel this scope immediately.

返回类型:

None

property cancel_called: bool

True if cancel() has been called.

property cancelled_caught: bool

True if this scope suppressed a cancellation exception it itself raised.

This is typically used to check if any work was interrupted, or to see if the scope was cancelled due to its deadline being reached. The value will, however, only be True if the cancellation was triggered by the scope itself (and not an outer scope).

property deadline: float

The time (clock value) when this scope is cancelled automatically.

Will be float('inf') if no timeout has been set.

property shield: bool

True if this scope is shielded from external cancellation.

While a scope is shielded, it will not receive cancellations from outside.

任务组

Task groups

anyio.create_task_group()

Create a task group.

返回类型:

TaskGroup

返回:

a task group

class anyio.abc.TaskGroup

基类:object

Groups several asynchronous tasks together.

变量:

cancel_scope (CancelScope) -- the cancel scope inherited by all child tasks

abstract async start(func, *args, name=None)

Start a new task and wait until it signals for readiness.

参数:
  • func (Callable[..., Awaitable[Any]]) -- a coroutine function

  • args (object) -- positional arguments to call the function with

  • name (object) -- name of the task, for the purposes of introspection and debugging

返回类型:

Any

返回:

the value passed to task_status.started()

抛出:

RuntimeError -- if the task finishes without calling task_status.started()

Added in version 3.0.

abstract start_soon(func, *args, name=None)

Start a new task in this task group.

参数:
  • func (Callable[[Unpack[TypeVarTuple]], Awaitable[Any]]) -- a coroutine function

  • args (Unpack[TypeVarTuple]) -- positional arguments to call the function with

  • name (object) -- name of the task, for the purposes of introspection and debugging

返回类型:

None

Added in version 3.0.

class anyio.abc.TaskStatus(*args, **kwargs)

基类:Protocol[T_contra]

started(value=None)

Signal that the task has started.

参数:

value (Optional[TypeVar(T_contra, contravariant=True)]) -- object passed back to the starter of the task

返回类型:

None

在工作线程中运行代码

Running code in worker threads

async anyio.to_thread.run_sync(func, *args, abandon_on_cancel=False, cancellable=None, limiter=None)

Call the given function with the given arguments in a worker thread.

If the cancellable option is enabled and the task waiting for its completion is cancelled, the thread will still run its course but its return value (or any raised exception) will be ignored.

参数:
  • func (Callable[[Unpack[TypeVarTuple]], TypeVar(T_Retval)]) -- a callable

  • args (Unpack[TypeVarTuple]) -- positional arguments for the callable

  • abandon_on_cancel (bool) -- True to abandon the thread (leaving it to run unchecked on own) if the host task is cancelled, False to ignore cancellations in the host task until the operation has completed in the worker thread

  • cancellable (bool | None) -- deprecated alias of abandon_on_cancel; will override abandon_on_cancel if both parameters are passed

  • limiter (CapacityLimiter | None) -- capacity limiter to use to limit the total amount of threads running (if omitted, the default limiter is used)

返回类型:

TypeVar(T_Retval)

返回:

an awaitable that yields the return value of the function.

anyio.to_thread.current_default_thread_limiter()

Return the capacity limiter that is used by default to limit the number of concurrent threads.

返回类型:

CapacityLimiter

返回:

a capacity limiter object

在工作进程中运行代码

Running code in worker processes

async anyio.to_process.run_sync(func, *args, cancellable=False, limiter=None)

Call the given function with the given arguments in a worker process.

If the cancellable option is enabled and the task waiting for its completion is cancelled, the worker process running it will be abruptly terminated using SIGKILL (or terminateProcess() on Windows).

参数:
  • func (Callable[[Unpack[TypeVarTuple]], TypeVar(T_Retval)]) -- a callable

  • args (Unpack[TypeVarTuple]) -- positional arguments for the callable

  • cancellable (bool) -- True to allow cancellation of the operation while it's running

  • limiter (CapacityLimiter | None) -- capacity limiter to use to limit the total amount of processes running (if omitted, the default limiter is used)

返回类型:

TypeVar(T_Retval)

返回:

an awaitable that yields the return value of the function.

anyio.to_process.current_default_process_limiter()

Return the capacity limiter that is used by default to limit the number of worker processes.

返回类型:

CapacityLimiter

返回:

a capacity limiter object

从其他线程运行异步代码

Running asynchronous code from other threads

anyio.from_thread.run(func, *args)

Call a coroutine function from a worker thread.

参数:
  • func (Callable[[Unpack[TypeVarTuple]], Awaitable[TypeVar(T_Retval)]]) -- a coroutine function

  • args (Unpack[TypeVarTuple]) -- positional arguments for the callable

返回类型:

TypeVar(T_Retval)

返回:

the return value of the coroutine function

anyio.from_thread.run_sync(func, *args)

Call a function in the event loop thread from a worker thread.

参数:
  • func (Callable[[Unpack[TypeVarTuple]], TypeVar(T_Retval)]) -- a callable

  • args (Unpack[TypeVarTuple]) -- positional arguments for the callable

返回类型:

TypeVar(T_Retval)

返回:

the return value of the callable

anyio.from_thread.check_cancelled()

Check if the cancel scope of the host task's running the current worker thread has been cancelled.

If the host task's current cancel scope has indeed been cancelled, the backend-specific cancellation exception will be raised.

抛出:

RuntimeError -- if the current thread was not spawned by to_thread.run_sync()

返回类型:

None

anyio.from_thread.start_blocking_portal(backend='asyncio', backend_options=None)

Start a new event loop in a new thread and run a blocking portal in its main task.

The parameters are the same as for run().

参数:
  • backend (str) -- name of the backend

  • backend_options (dict[str, Any] | None) -- backend options

返回类型:

Generator[BlockingPortal, Any, None]

返回:

a context manager that yields a blocking portal

在 3.0 版本发生变更: Usage as a context manager is now required.

class anyio.from_thread.BlockingPortal

基类:object

An object that lets external threads run code in an asynchronous event loop.

call(func, *args)

Call the given function in the event loop thread.

If the callable returns a coroutine object, it is awaited on.

参数:

func (Callable[[Unpack[TypeVarTuple]], Union[Awaitable[TypeVar(T_Retval)], TypeVar(T_Retval)]]) -- any callable

抛出:

RuntimeError -- if the portal is not running or if this method is called from within the event loop thread

返回类型:

TypeVar(T_Retval)

async sleep_until_stopped()

Sleep until stop() is called.

返回类型:

None

start_task(func, *args, name=None)

Start a task in the portal's task group and wait until it signals for readiness.

This method works the same way as abc.TaskGroup.start().

参数:
  • func (Callable[..., Awaitable[TypeVar(T_Retval)]]) -- the target function

  • args (object) -- positional arguments passed to func

  • name (object) -- name of the task (will be coerced to a string if not None)

返回:

a tuple of (future, task_status_value) where the task_status_value is the value passed to task_status.started() from within the target function

返回类型:

tuple[concurrent.futures.Future[T_Retval], Any]

Added in version 3.0.

start_task_soon(func, *args, name=None)

Start a task in the portal's task group.

The task will be run inside a cancel scope which can be cancelled by cancelling the returned future.

参数:
  • func (Callable[[Unpack[TypeVarTuple]], Union[Awaitable[TypeVar(T_Retval)], TypeVar(T_Retval)]]) -- the target function

  • args (Unpack[TypeVarTuple]) -- positional arguments passed to func

  • name (object) -- name of the task (will be coerced to a string if not None)

返回:

a future that resolves with the return value of the callable if the task completes successfully, or with the exception raised in the task

抛出:

RuntimeError -- if the portal is not running or if this method is called from within the event loop thread

返回类型:

concurrent.futures.Future[T_Retval]

Added in version 3.0.

async stop(cancel_remaining=False)

Signal the portal to shut down.

This marks the portal as no longer accepting new calls and exits from sleep_until_stopped().

参数:

cancel_remaining (bool) -- True to cancel all the remaining tasks, False to let them finish before returning

返回类型:

None

wrap_async_context_manager(cm)

Wrap an async context manager as a synchronous context manager via this portal.

Spawns a task that will call both __aenter__() and __aexit__(), stopping in the middle until the synchronous context manager exits.

参数:

cm (AsyncContextManager[TypeVar(T_co, covariant=True)]) -- an asynchronous context manager

返回类型:

ContextManager[TypeVar(T_co, covariant=True)]

返回:

a synchronous context manager

Added in version 2.1.

class anyio.from_thread.BlockingPortalProvider(backend='asyncio', backend_options=None)

基类:object

A manager for a blocking portal. Used as a context manager. The first thread to enter this context manager causes a blocking portal to be started with the specific parameters, and the last thread to exit causes the portal to be shut down. Thus, there will be exactly one blocking portal running in this context as long as at least one thread has entered this context manager.

The parameters are the same as for run().

参数:
  • backend (str) -- name of the backend

  • backend_options (dict[str, Any] | None) -- backend options

Added in version 4.4.

异步文件 I/O

Async file I/O

async anyio.open_file(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Open a file asynchronously.

The arguments are exactly the same as for the builtin open().

返回类型:

AsyncFile[Any]

返回:

an asynchronous file object

anyio.wrap_file(file)

Wrap an existing file as an asynchronous file.

参数:

file (IO[AnyStr]) -- an existing file-like object

返回类型:

AsyncFile[AnyStr]

返回:

an asynchronous file object

class anyio.AsyncFile(fp)

基类:AsyncResource, Generic

An asynchronous file object.

This class wraps a standard file object and provides async friendly versions of the following blocking methods (where available on the original file object):

  • read

  • read1

  • readline

  • readlines

  • readinto

  • readinto1

  • write

  • writelines

  • truncate

  • seek

  • tell

  • flush

All other methods are directly passed through.

This class supports the asynchronous context manager protocol which closes the underlying file at the end of the context block.

This class also supports asynchronous iteration:

async with await open_file(...) as f:
    async for line in f:
        print(line)
async aclose()

Close the resource.

返回类型:

None

property wrapped: IO

The wrapped file object.

class anyio.Path(*args)

基类:object

An asynchronous version of pathlib.Path.

This class cannot be substituted for pathlib.Path or pathlib.PurePath, but it is compatible with the os.PathLike interface.

It implements the Python 3.10 version of pathlib.Path interface, except for the deprecated link_to() method.

Some methods may be unavailable or have limited functionality, based on the Python version:

  • from_uri() (available on Python 3.13 or later)

  • full_match() (available on Python 3.13 or later)

  • is_junction() (available on Python 3.12 or later)

  • match() (the case_sensitive paramater is only available on Python 3.13 or later)

  • relative_to() (the walk_up parameter is only available on Python 3.12 or later)

  • walk() (available on Python 3.12 or later)

Any methods that do disk I/O need to be awaited on. These methods are:

Additionally, the following methods return an async iterator yielding Path objects:

流和流包装器

Streams and stream wrappers

anyio.create_memory_object_stream(max_buffer_size: float = 0, item_type: object = None) tuple[MemoryObjectSendStream[T_Item], MemoryObjectReceiveStream[T_Item]]

Create a memory object stream.

The stream's item type can be annotated like create_memory_object_stream[T_Item]().

参数:
  • max_buffer_size -- number of items held in the buffer until send() starts blocking

  • item_type --

    old way of marking the streams with the right generic type for static typing (does nothing on AnyIO 4)

    自 4.0 版本弃用: Use create_memory_object_stream[YourItemType](...) instead.

返回:

a tuple of (send stream, receive stream)

class anyio.abc.UnreliableObjectReceiveStream

基类:Generic[T_co], AsyncResource, TypedAttributeProvider

An interface for receiving objects.

This interface makes no guarantees that the received messages arrive in the order in which they were sent, or that no messages are missed.

Asynchronously iterating over objects of this type will yield objects matching the given type parameter.

abstract async receive()

Receive the next item.

抛出:
返回类型:

TypeVar(T_co, covariant=True)

class anyio.abc.UnreliableObjectSendStream

基类:Generic[T_contra], AsyncResource, TypedAttributeProvider

An interface for sending objects.

This interface makes no guarantees that the messages sent will reach the recipient(s) in the same order in which they were sent, or at all.

abstract async send(item)

Send an item to the peer(s).

参数:

item (TypeVar(T_contra, contravariant=True)) -- the item to send

抛出:
返回类型:

None

class anyio.abc.UnreliableObjectStream

基类:UnreliableObjectReceiveStream[T_Item], UnreliableObjectSendStream[T_Item]

A bidirectional message stream which does not guarantee the order or reliability of message delivery.

class anyio.abc.ObjectReceiveStream

基类:UnreliableObjectReceiveStream[T_co]

A receive message stream which guarantees that messages are received in the same order in which they were sent, and that no messages are missed.

class anyio.abc.ObjectSendStream

基类:UnreliableObjectSendStream[T_contra]

A send message stream which guarantees that messages are delivered in the same order in which they were sent, without missing any messages in the middle.

class anyio.abc.ObjectStream

基类:ObjectReceiveStream[T_Item], ObjectSendStream[T_Item], UnreliableObjectStream[T_Item]

A bidirectional message stream which guarantees the order and reliability of message delivery.

abstract async send_eof()

Send an end-of-file indication to the peer.

You should not try to send any further data to this stream after calling this method. This method is idempotent (does nothing on successive calls).

返回类型:

None

class anyio.abc.ByteReceiveStream

基类:AsyncResource, TypedAttributeProvider

An interface for receiving bytes from a single peer.

Iterating this byte stream will yield a byte string of arbitrary length, but no more than 65536 bytes.

abstract async receive(max_bytes=65536)

Receive at most max_bytes bytes from the peer.

备注

Implementors of this interface should not return an empty bytes object, and users should ignore them.

参数:

max_bytes (int) -- maximum number of bytes to receive

返回类型:

bytes

返回:

the received bytes

抛出:

EndOfStream -- if this stream has been closed from the other end

class anyio.abc.ByteSendStream

基类:AsyncResource, TypedAttributeProvider

An interface for sending bytes to a single peer.

abstract async send(item)

Send the given bytes to the peer.

参数:

item (bytes) -- the bytes to send

返回类型:

None

class anyio.abc.ByteStream

基类:ByteReceiveStream, ByteSendStream

A bidirectional byte stream.

abstract async send_eof()

Send an end-of-file indication to the peer.

You should not try to send any further data to this stream after calling this method. This method is idempotent (does nothing on successive calls).

返回类型:

None

class anyio.abc.Listener

基类:Generic[T_co], AsyncResource, TypedAttributeProvider

An interface for objects that let you accept incoming connections.

abstract async serve(handler, task_group=None)

Accept incoming connections as they come in and start tasks to handle them.

参数:
  • handler (Callable[[TypeVar(T_co, covariant=True)], Any]) -- a callable that will be used to handle each accepted connection

  • task_group (TaskGroup | None) -- the task group that will be used to start tasks for handling each accepted connection (if omitted, an ad-hoc task group will be created)

返回类型:

None

anyio.abc.AnyUnreliableByteReceiveStream

UnreliableObjectReceiveStream[bytes] | ByteReceiveStream 的别名

anyio.abc.AnyUnreliableByteSendStream

UnreliableObjectSendStream[bytes] | ByteSendStream 的别名

anyio.abc.AnyUnreliableByteStream

UnreliableObjectStream[bytes] | ByteStream 的别名

anyio.abc.AnyByteReceiveStream

ObjectReceiveStream[bytes] | ByteReceiveStream 的别名

anyio.abc.AnyByteSendStream

ObjectSendStream[bytes] | ByteSendStream 的别名

anyio.abc.AnyByteStream

ObjectStream[bytes] | ByteStream 的别名

class anyio.streams.buffered.BufferedByteReceiveStream(receive_stream)

基类:ByteReceiveStream

Wraps any bytes-based receive stream and uses a buffer to provide sophisticated receiving capabilities in the form of a byte stream.

async aclose()

Close the resource.

返回类型:

None

property buffer: bytes

The bytes currently in the buffer.

property extra_attributes: Mapping[Any, Callable[[], Any]]

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

async receive(max_bytes=65536)

Receive at most max_bytes bytes from the peer.

备注

Implementors of this interface should not return an empty bytes object, and users should ignore them.

参数:

max_bytes (int) -- maximum number of bytes to receive

返回类型:

bytes

返回:

the received bytes

抛出:

EndOfStream -- if this stream has been closed from the other end

async receive_exactly(nbytes)

Read exactly the given amount of bytes from the stream.

参数:

nbytes (int) -- the number of bytes to read

返回类型:

bytes

返回:

the bytes read

抛出:

IncompleteRead -- if the stream was closed before the requested amount of bytes could be read from the stream

async receive_until(delimiter, max_bytes)

Read from the stream until the delimiter is found or max_bytes have been read.

参数:
  • delimiter (bytes) -- the marker to look for in the stream

  • max_bytes (int) -- maximum number of bytes that will be read before raising DelimiterNotFound

返回类型:

bytes

返回:

the bytes read (not including the delimiter)

抛出:
  • IncompleteRead -- if the stream was closed before the delimiter was found

  • DelimiterNotFound -- if the delimiter is not found within the bytes read up to the maximum allowed

class anyio.streams.file.FileStreamAttribute

基类:TypedAttributeSet

file: BinaryIO = <object object>

the open file descriptor

fileno: int = <object object>

the file number, if available (file must be a real file or a TTY)

path: Path = <object object>

the path of the file on the file system, if available (file must be a real file)

class anyio.streams.file.FileReadStream(file)

基类:_BaseFileStream, ByteReceiveStream

A byte stream that reads from a file in the file system.

参数:

file (BinaryIO) -- a file that has been opened for reading in binary mode

Added in version 3.0.

async classmethod from_path(path)

Create a file read stream by opening the given file.

参数:

path (str | PathLike[str]) -- path of the file to read from

返回类型:

FileReadStream

async receive(max_bytes=65536)

Receive at most max_bytes bytes from the peer.

备注

Implementors of this interface should not return an empty bytes object, and users should ignore them.

参数:

max_bytes (int) -- maximum number of bytes to receive

返回类型:

bytes

返回:

the received bytes

抛出:

EndOfStream -- if this stream has been closed from the other end

async seek(position, whence=0)

Seek the file to the given position.

备注

Not all file descriptors are seekable.

参数:
  • position (int) -- position to seek the file to

  • whence (int) -- controls how position is interpreted

返回类型:

int

返回:

the new absolute position

抛出:

OSError -- if the file is not seekable

async tell()

Return the current stream position.

备注

Not all file descriptors are seekable.

返回类型:

int

返回:

the current absolute position

抛出:

OSError -- if the file is not seekable

class anyio.streams.file.FileWriteStream(file)

基类:_BaseFileStream, ByteSendStream

A byte stream that writes to a file in the file system.

参数:

file (BinaryIO) -- a file that has been opened for writing in binary mode

Added in version 3.0.

async classmethod from_path(path, append=False)

Create a file write stream by opening the given file for writing.

参数:
  • path (str | PathLike[str]) -- path of the file to write to

  • append (bool) -- if True, open the file for appending; if False, any existing file at the given path will be truncated

返回类型:

FileWriteStream

async send(item)

Send the given bytes to the peer.

参数:

item (bytes) -- the bytes to send

返回类型:

None

class anyio.streams.memory.MemoryObjectReceiveStream(_state)

基类:Generic[T_co], ObjectReceiveStream[T_co]

async aclose()

Close the resource.

返回类型:

None

clone()

Create a clone of this receive stream.

Each clone can be closed separately. Only when all clones have been closed will the receiving end of the memory stream be considered closed by the sending ends.

返回类型:

MemoryObjectReceiveStream[TypeVar(T_co, covariant=True)]

返回:

the cloned stream

close()

Close the stream.

This works the exact same way as aclose(), but is provided as a special case for the benefit of synchronous callbacks.

返回类型:

None

async receive()

Receive the next item.

抛出:
返回类型:

TypeVar(T_co, covariant=True)

receive_nowait()

Receive the next item if it can be done without waiting.

返回类型:

TypeVar(T_co, covariant=True)

返回:

the received item

抛出:
  • ClosedResourceError -- if this send stream has been closed

  • EndOfStream -- if the buffer is empty and this stream has been closed from the sending end

  • WouldBlock -- if there are no items in the buffer and no tasks waiting to send

statistics()

Return statistics about the current state of this stream. :rtype: MemoryObjectStreamStatistics

Added in version 3.0.

class anyio.streams.memory.MemoryObjectSendStream(_state)

基类:Generic[T_contra], ObjectSendStream[T_contra]

async aclose()

Close the resource.

返回类型:

None

clone()

Create a clone of this send stream.

Each clone can be closed separately. Only when all clones have been closed will the sending end of the memory stream be considered closed by the receiving ends.

返回类型:

MemoryObjectSendStream[TypeVar(T_contra, contravariant=True)]

返回:

the cloned stream

close()

Close the stream.

This works the exact same way as aclose(), but is provided as a special case for the benefit of synchronous callbacks.

返回类型:

None

async send(item)

Send an item to the stream.

If the buffer is full, this method blocks until there is again room in the buffer or the item can be sent directly to a receiver.

参数:

item (TypeVar(T_contra, contravariant=True)) -- the item to send

抛出:
返回类型:

None

send_nowait(item)

Send an item immediately if it can be done without waiting.

参数:

item (TypeVar(T_contra, contravariant=True)) -- the item to send

抛出:
返回类型:

None

statistics()

Return statistics about the current state of this stream. :rtype: MemoryObjectStreamStatistics

Added in version 3.0.

class anyio.streams.memory.MemoryObjectStreamStatistics(current_buffer_used, max_buffer_size, open_send_streams, open_receive_streams, tasks_waiting_send, tasks_waiting_receive)

基类:NamedTuple

current_buffer_used: int

number of items stored in the buffer

max_buffer_size: float

maximum number of items that can be stored on this stream (or math.inf)

open_receive_streams: int

number of unclosed clones of the receive stream

open_send_streams: int

number of unclosed clones of the send stream

tasks_waiting_receive: int

number of tasks blocked on MemoryObjectReceiveStream.receive()

tasks_waiting_send: int

number of tasks blocked on MemoryObjectSendStream.send()

class anyio.streams.stapled.MultiListener(listeners)

基类:Generic[T_Stream], Listener[T_Stream]

Combines multiple listeners into one, serving connections from all of them at once.

Any MultiListeners in the given collection of listeners will have their listeners moved into this one.

Extra attributes are provided from each listener, with each successive listener overriding any conflicting attributes from the previous one.

参数:

listeners (Sequence[Listener[T_Stream]]) -- listeners to serve

async aclose()

Close the resource.

返回类型:

None

property extra_attributes: Mapping[Any, Callable[[], Any]]

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

async serve(handler, task_group=None)

Accept incoming connections as they come in and start tasks to handle them.

参数:
  • handler (Callable[[TypeVar(T_Stream)], Any]) -- a callable that will be used to handle each accepted connection

  • task_group (TaskGroup | None) -- the task group that will be used to start tasks for handling each accepted connection (if omitted, an ad-hoc task group will be created)

返回类型:

None

class anyio.streams.stapled.StapledByteStream(send_stream, receive_stream)

基类:ByteStream

Combines two byte streams into a single, bidirectional byte stream.

Extra attributes will be provided from both streams, with the receive stream providing the values in case of a conflict.

参数:
async aclose()

Close the resource.

返回类型:

None

property extra_attributes: Mapping[Any, Callable[[], Any]]

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

async receive(max_bytes=65536)

Receive at most max_bytes bytes from the peer.

备注

Implementors of this interface should not return an empty bytes object, and users should ignore them.

参数:

max_bytes (int) -- maximum number of bytes to receive

返回类型:

bytes

返回:

the received bytes

抛出:

EndOfStream -- if this stream has been closed from the other end

async send(item)

Send the given bytes to the peer.

参数:

item (bytes) -- the bytes to send

返回类型:

None

async send_eof()

Send an end-of-file indication to the peer.

You should not try to send any further data to this stream after calling this method. This method is idempotent (does nothing on successive calls).

返回类型:

None

class anyio.streams.stapled.StapledObjectStream(send_stream, receive_stream)

基类:Generic[T_Item], ObjectStream[T_Item]

Combines two object streams into a single, bidirectional object stream.

Extra attributes will be provided from both streams, with the receive stream providing the values in case of a conflict.

参数:
async aclose()

Close the resource.

返回类型:

None

property extra_attributes: Mapping[Any, Callable[[], Any]]

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

async receive()

Receive the next item.

抛出:
返回类型:

TypeVar(T_Item)

async send(item)

Send an item to the peer(s).

参数:

item (TypeVar(T_Item)) -- the item to send

抛出:
返回类型:

None

async send_eof()

Send an end-of-file indication to the peer.

You should not try to send any further data to this stream after calling this method. This method is idempotent (does nothing on successive calls).

返回类型:

None

class anyio.streams.text.TextReceiveStream(transport_stream, encoding='utf-8', errors='strict')

基类:ObjectReceiveStream[str]

Stream wrapper that decodes bytes to strings using the given encoding.

Decoding is done using IncrementalDecoder which returns any completely received unicode characters as soon as they come in.

参数:
  • transport_stream (Union[ObjectReceiveStream[bytes], ByteReceiveStream]) -- any bytes-based receive stream

  • encoding (InitVar) -- character encoding to use for decoding bytes to strings (defaults to utf-8)

  • errors (InitVar) -- handling scheme for decoding errors (defaults to strict; see the codecs module documentation for a comprehensive list of options)

async aclose()

Close the resource.

返回类型:

None

property extra_attributes: Mapping[Any, Callable[[], Any]]

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

async receive()

Receive the next item.

抛出:
返回类型:

str

class anyio.streams.text.TextSendStream(transport_stream, encoding='utf-8', errors='strict')

基类:ObjectSendStream[str]

Sends strings to the wrapped stream as bytes using the given encoding.

参数:
  • transport_stream (AnyByteSendStream) -- any bytes-based send stream

  • encoding (str) -- character encoding to use for encoding strings to bytes (defaults to utf-8)

  • errors (str) -- handling scheme for encoding errors (defaults to strict; see the codecs module documentation for a comprehensive list of options)

async aclose()

Close the resource.

返回类型:

None

property extra_attributes: Mapping[Any, Callable[[], Any]]

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

async send(item)

Send an item to the peer(s).

参数:

item (str) -- the item to send

抛出:
返回类型:

None

class anyio.streams.text.TextStream(transport_stream, encoding='utf-8', errors='strict')

基类:ObjectStream[str]

A bidirectional stream that decodes bytes to strings on receive and encodes strings to bytes on send.

Extra attributes will be provided from both streams, with the receive stream providing the values in case of a conflict.

参数:
  • transport_stream (AnyByteStream) -- any bytes-based stream

  • encoding (str) -- character encoding to use for encoding/decoding strings to/from bytes (defaults to utf-8)

  • errors (str) -- handling scheme for encoding errors (defaults to strict; see the codecs module documentation for a comprehensive list of options)

async aclose()

Close the resource.

返回类型:

None

property extra_attributes: Mapping[Any, Callable[[], Any]]

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

async receive()

Receive the next item.

抛出:
返回类型:

str

async send(item)

Send an item to the peer(s).

参数:

item (str) -- the item to send

抛出:
返回类型:

None

async send_eof()

Send an end-of-file indication to the peer.

You should not try to send any further data to this stream after calling this method. This method is idempotent (does nothing on successive calls).

返回类型:

None

class anyio.streams.tls.TLSAttribute

基类:TypedAttributeSet

Contains Transport Layer Security related attributes.

alpn_protocol: str | None = <object object>

the selected ALPN protocol

channel_binding_tls_unique: bytes = <object object>

the channel binding for type tls-unique

cipher: tuple[str, str, int] = <object object>

the selected cipher

peer_certificate_binary: bytes | None = <object object>

the peer certificate in binary form

server_side: bool = <object object>

True if this is the server side of the connection

shared_ciphers: list[tuple[str, str, int]] | None = <object object>

ciphers shared by the client during the TLS handshake (None if this is the client side)

ssl_object: SSLObject = <object object>

the SSLObject used for encryption

standard_compatible: bool = <object object>

True if this stream does (and expects) a closing TLS handshake when the stream is being closed

tls_version: str = <object object>

the TLS protocol version (e.g. TLSv1.2)

class anyio.streams.tls.TLSStream(transport_stream, standard_compatible, _ssl_object, _read_bio, _write_bio)

基类:ByteStream

A stream wrapper that encrypts all sent data and decrypts received data.

This class has no public initializer; use wrap() instead. All extra attributes from TLSAttribute are supported.

变量:

transport_stream (AnyByteStream) -- the wrapped stream

async aclose()

Close the resource.

返回类型:

None

property extra_attributes: Mapping[Any, Callable[[], Any]]

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

async receive(max_bytes=65536)

Receive at most max_bytes bytes from the peer.

备注

Implementors of this interface should not return an empty bytes object, and users should ignore them.

参数:

max_bytes (int) -- maximum number of bytes to receive

返回类型:

bytes

返回:

the received bytes

抛出:

EndOfStream -- if this stream has been closed from the other end

async send(item)

Send the given bytes to the peer.

参数:

item (bytes) -- the bytes to send

返回类型:

None

async send_eof()

Send an end-of-file indication to the peer.

You should not try to send any further data to this stream after calling this method. This method is idempotent (does nothing on successive calls).

返回类型:

None

async unwrap()

Does the TLS closing handshake.

返回类型:

tuple[Union[ObjectStream[bytes], ByteStream], bytes]

返回:

a tuple of (wrapped byte stream, bytes left in the read buffer)

async classmethod wrap(transport_stream, *, server_side=None, hostname=None, ssl_context=None, standard_compatible=True)

Wrap an existing stream with Transport Layer Security.

This performs a TLS handshake with the peer.

参数:
  • transport_stream (Union[ObjectStream[bytes], ByteStream]) -- a bytes-transporting stream to wrap

  • server_side (bool | None) -- True if this is the server side of the connection, False if this is the client side (if omitted, will be set to False if hostname has been provided, False otherwise). Used only to create a default context when an explicit context has not been provided.

  • hostname (str | None) -- host name of the peer (if host name checking is desired)

  • ssl_context (SSLContext | None) -- the SSLContext object to use (if not provided, a secure default will be created)

  • standard_compatible (bool) -- if False, skip the closing handshake when closing the connection, and don't raise an exception if the peer does the same

抛出:

SSLError -- if the TLS handshake fails

返回类型:

TLSStream

class anyio.streams.tls.TLSListener(listener, ssl_context, standard_compatible=True, handshake_timeout=30)

基类:Listener[TLSStream]

A convenience listener that wraps another listener and auto-negotiates a TLS session on every accepted connection.

If the TLS handshake times out or raises an exception, handle_handshake_error() is called to do whatever post-mortem processing is deemed necessary.

Supports only the standard_compatible extra attribute.

参数:
async aclose()

Close the resource.

返回类型:

None

property extra_attributes: Mapping[Any, Callable[[], Any]]

A mapping of the extra attributes to callables that return the corresponding values.

If the provider wraps another provider, the attributes from that wrapper should also be included in the returned mapping (but the wrapper may override the callables from the wrapped instance).

async static handle_handshake_error(exc, stream)

Handle an exception raised during the TLS handshake.

This method does 3 things:

  1. Forcefully closes the original stream

  2. Logs the exception (unless it was a cancellation exception) using the anyio.streams.tls logger

  3. Reraises the exception if it was a base exception or a cancellation exception

参数:
返回类型:

None

async serve(handler, task_group=None)

Accept incoming connections as they come in and start tasks to handle them.

参数:
  • handler (Callable[[TLSStream], Any]) -- a callable that will be used to handle each accepted connection

  • task_group (TaskGroup | None) -- the task group that will be used to start tasks for handling each accepted connection (if omitted, an ad-hoc task group will be created)

返回类型:

None

套接字和网络

Sockets and networking

async anyio.connect_tcp(remote_host, remote_port, *, local_host=None, tls=False, ssl_context=None, tls_standard_compatible=True, tls_hostname=None, happy_eyeballs_delay=0.25)

Connect to a host using the TCP protocol.

This function implements the stateless version of the Happy Eyeballs algorithm (RFC 6555). If remote_host is a host name that resolves to multiple IP addresses, each one is tried until one connection attempt succeeds. If the first attempt does not connected within 250 milliseconds, a second attempt is started using the next address in the list, and so on. On IPv6 enabled systems, an IPv6 address (if available) is tried first.

When the connection has been established, a TLS handshake will be done if either ssl_context or tls_hostname is not None, or if tls is True.

参数:
  • remote_host (Union[str, IPv4Address, IPv6Address]) -- the IP address or host name to connect to

  • remote_port (int) -- port on the target host to connect to

  • local_host (Union[str, IPv4Address, IPv6Address, None]) -- the interface address or name to bind the socket to before connecting

  • tls (bool) -- True to do a TLS handshake with the connected stream and return a TLSStream instead

  • ssl_context (SSLContext | None) -- the SSL context object to use (if omitted, a default context is created)

  • tls_standard_compatible (bool) -- If True, performs the TLS shutdown handshake before closing the stream and requires that the server does this as well. Otherwise, SSLEOFError may be raised during reads from the stream. Some protocols, such as HTTP, require this option to be False. See wrap_socket() for details.

  • tls_hostname (str | None) -- host name to check the server certificate against (defaults to the value of remote_host)

  • happy_eyeballs_delay (float) -- delay (in seconds) before starting the next connection attempt

返回类型:

SocketStream | TLSStream

返回:

a socket stream object if no TLS handshake was done, otherwise a TLS stream

抛出:

OSError -- if the connection attempt fails

async anyio.connect_unix(path)

Connect to the given UNIX socket.

Not available on Windows.

参数:

path (str | bytes | PathLike[Any]) -- path to the socket

返回类型:

UNIXSocketStream

返回:

a socket stream object

async anyio.create_tcp_listener(*, local_host=None, local_port=0, family=AddressFamily.AF_UNSPEC, backlog=65536, reuse_port=False)

Create a TCP socket listener.

参数:
  • local_port (int) -- port number to listen on

  • local_host (Union[str, IPv4Address, IPv6Address, None]) -- IP address of the interface to listen on. If omitted, listen on all IPv4 and IPv6 interfaces. To listen on all interfaces on a specific address family, use 0.0.0.0 for IPv4 or :: for IPv6.

  • family (Literal[<AddressFamily.AF_UNSPEC: 0>, <AddressFamily.AF_INET: 2>, <AddressFamily.AF_INET6: 10>]) -- address family (used if local_host was omitted)

  • backlog (int) -- maximum number of queued incoming connections (up to a maximum of 2**16, or 65536)

  • reuse_port (bool) -- True to allow multiple sockets to bind to the same address/port (not supported on Windows)

返回类型:

MultiListener[SocketStream]

返回:

a list of listener objects

async anyio.create_unix_listener(path, *, mode=None, backlog=65536)

Create a UNIX socket listener.

Not available on Windows.

参数:
  • path (str | bytes | PathLike[Any]) -- path of the socket

  • mode (int | None) -- permissions to set on the socket

  • backlog (int) -- maximum number of queued incoming connections (up to a maximum of 2**16, or 65536)

返回类型:

SocketListener

返回:

a listener object

在 3.0 版本发生变更: If a socket already exists on the file system in the given path, it will be removed first.

async anyio.create_udp_socket(family=AddressFamily.AF_UNSPEC, *, local_host=None, local_port=0, reuse_port=False)

Create a UDP socket.

If port has been given, the socket will be bound to this port on the local machine, making this socket suitable for providing UDP based services.

参数:
  • family (Literal[<AddressFamily.AF_UNSPEC: 0>, <AddressFamily.AF_INET: 2>, <AddressFamily.AF_INET6: 10>]) -- address family (AF_INET or AF_INET6) – automatically determined from local_host if omitted

  • local_host (Union[str, IPv4Address, IPv6Address, None]) -- IP address or host name of the local interface to bind to

  • local_port (int) -- local port to bind to

  • reuse_port (bool) -- True to allow multiple sockets to bind to the same address/port (not supported on Windows)

返回类型:

UDPSocket

返回:

a UDP socket

async anyio.create_connected_udp_socket(remote_host, remote_port, *, family=AddressFamily.AF_UNSPEC, local_host=None, local_port=0, reuse_port=False)

Create a connected UDP socket.

Connected UDP sockets can only communicate with the specified remote host/port, an any packets sent from other sources are dropped.

参数:
  • remote_host (Union[str, IPv4Address, IPv6Address]) -- remote host to set as the default target

  • remote_port (int) -- port on the remote host to set as the default target

  • family (Literal[<AddressFamily.AF_UNSPEC: 0>, <AddressFamily.AF_INET: 2>, <AddressFamily.AF_INET6: 10>]) -- address family (AF_INET or AF_INET6) – automatically determined from local_host or remote_host if omitted

  • local_host (Union[str, IPv4Address, IPv6Address, None]) -- IP address or host name of the local interface to bind to

  • local_port (int) -- local port to bind to

  • reuse_port (bool) -- True to allow multiple sockets to bind to the same address/port (not supported on Windows)

返回类型:

ConnectedUDPSocket

返回:

a connected UDP socket

async anyio.getaddrinfo(host, port, *, family=0, type=0, proto=0, flags=0)

Look up a numeric IP address given a host name.

Internationalized domain names are translated according to the (non-transitional) IDNA 2008 standard.

备注

4-tuple IPv6 socket addresses are automatically converted to 2-tuples of (host, port), unlike what socket.getaddrinfo() does.

参数:
  • host (bytes | str | None) -- host name

  • port (str | int | None) -- port number

  • family (int | AddressFamily) -- socket family ('AF_INET`, ...)

  • type (int | SocketKind) -- socket type (SOCK_STREAM, ...)

  • proto (int) -- protocol number

  • flags (int) -- flags to pass to upstream getaddrinfo()

返回类型:

list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int]]]

返回:

list of tuples containing (family, type, proto, canonname, sockaddr)

anyio.getnameinfo(sockaddr, flags=0)

Look up the host name of an IP address.

参数:
  • sockaddr (Tuple[str, int]) -- socket address (e.g. (ipaddress, port) for IPv4)

  • flags (int) -- flags to pass to upstream getnameinfo()

返回类型:

Awaitable[tuple[str, str]]

返回:

a tuple of (host name, service name)

anyio.wait_socket_readable(sock)

Wait until the given socket has data to be read.

This does NOT work on Windows when using the asyncio backend with a proactor event loop (default on py3.8+).

警告

Only use this on raw sockets that have not been wrapped by any higher level constructs like socket streams!

参数:

sock (socket) -- a socket object

抛出:
  • ClosedResourceError -- if the socket was closed while waiting for the socket to become readable

  • BusyResourceError -- if another task is already waiting for the socket to become readable

返回类型:

Awaitable[None]

anyio.wait_socket_writable(sock)

Wait until the given socket can be written to.

This does NOT work on Windows when using the asyncio backend with a proactor event loop (default on py3.8+).

警告

Only use this on raw sockets that have not been wrapped by any higher level constructs like socket streams!

参数:

sock (socket) -- a socket object

抛出:
  • ClosedResourceError -- if the socket was closed while waiting for the socket to become writable

  • BusyResourceError -- if another task is already waiting for the socket to become writable

返回类型:

Awaitable[None]

class anyio.abc.SocketAttribute

基类:TypedAttributeSet

class anyio.abc.SocketStream

基类:ByteStream, _SocketProvider

Transports bytes over a socket.

Supports all relevant extra attributes from SocketAttribute.

class anyio.abc.SocketListener

基类:Listener[SocketStream], _SocketProvider

Listens to incoming socket connections.

Supports all relevant extra attributes from SocketAttribute.

abstract async accept()

Accept an incoming connection.

返回类型:

SocketStream

async serve(handler, task_group=None)

Accept incoming connections as they come in and start tasks to handle them.

参数:
  • handler (Callable[[SocketStream], Any]) -- a callable that will be used to handle each accepted connection

  • task_group (TaskGroup | None) -- the task group that will be used to start tasks for handling each accepted connection (if omitted, an ad-hoc task group will be created)

返回类型:

None

class anyio.abc.UDPSocket

基类:UnreliableObjectStream[Tuple[bytes, Tuple[str, int]]], _SocketProvider

Represents an unconnected UDP socket.

Supports all relevant extra attributes from SocketAttribute.

async sendto(data, host, port)

Alias for send() ((data, (host, port))).

返回类型:

None

class anyio.abc.ConnectedUDPSocket

基类:UnreliableObjectStream[bytes], _SocketProvider

Represents an connected UDP socket.

Supports all relevant extra attributes from SocketAttribute.

class anyio.abc.UNIXSocketStream

基类:SocketStream

abstract async receive_fds(msglen, maxfds)

Receive file descriptors along with a message from the peer.

参数:
  • msglen (int) -- length of the message to expect from the peer

  • maxfds (int) -- maximum number of file descriptors to expect from the peer

返回类型:

tuple[bytes, list[int]]

返回:

a tuple of (message, file descriptors)

abstract async send_fds(message, fds)

Send file descriptors along with a message to the peer.

参数:
  • message (bytes) -- a non-empty bytestring

  • fds (Collection[int | IOBase]) -- a collection of files (either numeric file descriptors or open file or socket objects)

返回类型:

None

子进程

Subprocesses

async anyio.run_process(command, *, input=None, stdout=-1, stderr=-1, check=True, cwd=None, env=None, startupinfo=None, creationflags=0, start_new_session=False, pass_fds=(), user=None, group=None, extra_groups=None, umask=-1)

Run an external command in a subprocess and wait until it completes.

参数:
返回类型:

CompletedProcess[bytes]

返回:

an object representing the completed process

抛出:

CalledProcessError -- if check is True and the process exits with a nonzero return code

async anyio.open_process(command, *, stdin=-1, stdout=-1, stderr=-1, cwd=None, env=None, startupinfo=None, creationflags=0, start_new_session=False, pass_fds=(), user=None, group=None, extra_groups=None, umask=-1)

Start an external command in a subprocess.

参数:
返回类型:

Process

返回:

an asynchronous process object

class anyio.abc.Process

基类:AsyncResource

An asynchronous version of subprocess.Popen.

abstract kill()

Kills the process.

On Windows, this calls TerminateProcess(). On POSIX systems, this sends SIGKILL to the process. :rtype: None

abstract property pid: int

The process ID of the process.

abstract property returncode: int | None

The return code of the process. If the process has not yet terminated, this will be None.

abstract send_signal(signal)

Send a signal to the subprocess.

参数:

signal (Signals) -- the signal number (e.g. signal.SIGHUP)

返回类型:

None

abstract property stderr: ByteReceiveStream | None

The stream for the standard error output of the process.

abstract property stdin: ByteSendStream | None

The stream for the standard input of the process.

abstract property stdout: ByteReceiveStream | None

The stream for the standard output of the process.

abstract terminate()

Terminates the process, gracefully if possible.

On Windows, this calls TerminateProcess(). On POSIX systems, this sends SIGTERM to the process. :rtype: None

abstract async wait()

Wait until the process exits.

返回类型:

int

返回:

the exit code of the process

同步

Synchronization

class anyio.Event

基类:object

is_set()

Return True if the flag is set, False if not.

返回类型:

bool

set()

Set the flag, notifying all listeners.

返回类型:

None

statistics()

Return statistics about the current state of this event.

返回类型:

EventStatistics

async wait()

Wait until the flag has been set.

If the flag has already been set when this method is called, it returns immediately.

返回类型:

None

class anyio.Lock(*, fast_acquire: bool = False)

基类:object

async acquire()

Acquire the lock.

返回类型:

None

acquire_nowait()

Acquire the lock, without blocking.

抛出:

WouldBlock -- if the operation would block

返回类型:

None

locked()

Return True if the lock is currently held.

返回类型:

bool

release()

Release the lock.

返回类型:

None

statistics()

Return statistics about the current state of this lock. :rtype: LockStatistics

Added in version 3.0.

class anyio.Condition(lock=None)

基类:object

async acquire()

Acquire the underlying lock.

返回类型:

None

acquire_nowait()

Acquire the underlying lock, without blocking.

抛出:

WouldBlock -- if the operation would block

返回类型:

None

locked()

Return True if the lock is set.

返回类型:

bool

notify(n=1)

Notify exactly n listeners.

返回类型:

None

notify_all()

Notify all the listeners.

返回类型:

None

release()

Release the underlying lock.

返回类型:

None

statistics()

Return statistics about the current state of this condition. :rtype: ConditionStatistics

Added in version 3.0.

async wait()

Wait for a notification.

返回类型:

None

class anyio.Semaphore(initial_value, *, max_value=None, fast_acquire=False)

基类:object

async acquire()

Decrement the semaphore value, blocking if necessary.

返回类型:

None

acquire_nowait()

Acquire the underlying lock, without blocking.

抛出:

WouldBlock -- if the operation would block

返回类型:

None

property max_value: int | None

The maximum value of the semaphore.

release()

Increment the semaphore value.

返回类型:

None

statistics()

Return statistics about the current state of this semaphore. :rtype: SemaphoreStatistics

Added in version 3.0.

property value: int

The current value of the semaphore.

class anyio.CapacityLimiter(total_tokens: float)

基类:object

async acquire()

Acquire a token for the current task, waiting if necessary for one to become available.

返回类型:

None

acquire_nowait()

Acquire a token for the current task without waiting for one to become available.

抛出:

WouldBlock -- if there are no tokens available for borrowing

返回类型:

None

async acquire_on_behalf_of(borrower)

Acquire a token, waiting if necessary for one to become available.

参数:

borrower (object) -- the entity borrowing a token

返回类型:

None

acquire_on_behalf_of_nowait(borrower)

Acquire a token without waiting for one to become available.

参数:

borrower (object) -- the entity borrowing a token

抛出:

WouldBlock -- if there are no tokens available for borrowing

返回类型:

None

property available_tokens: float

The number of tokens currently available to be borrowed

property borrowed_tokens: int

The number of tokens that have currently been borrowed.

release()

Release the token held by the current task.

抛出:

RuntimeError -- if the current task has not borrowed a token from this limiter.

返回类型:

None

release_on_behalf_of(borrower)

Release the token held by the given borrower.

抛出:

RuntimeError -- if the borrower has not borrowed a token from this limiter.

返回类型:

None

statistics()

Return statistics about the current state of this limiter. :rtype: CapacityLimiterStatistics

Added in version 3.0.

property total_tokens: float

The total number of tokens available for borrowing.

This is a read-write property. If the total number of tokens is increased, the proportionate number of tasks waiting on this limiter will be granted their tokens.

在 3.0 版本发生变更: The property is now writable.

class anyio.ResourceGuard(action='using')

基类:object

A context manager for ensuring that a resource is only used by a single task at a time.

Entering this context manager while the previous has not exited it yet will trigger BusyResourceError.

参数:

action (str) -- the action to guard against (visible in the BusyResourceError when triggered, e.g. "Another task is already {action} this resource")

Added in version 4.1.

class anyio.LockStatistics(locked, owner, tasks_waiting)

基类:object

变量:
  • locked (bool) -- flag indicating if this lock is locked or not

  • owner (TaskInfo) -- task currently holding the lock (or None if the lock is not held by any task)

  • tasks_waiting (int) -- number of tasks waiting on acquire()

class anyio.EventStatistics(tasks_waiting)

基类:object

变量:

tasks_waiting (int) -- number of tasks waiting on wait()

class anyio.ConditionStatistics(tasks_waiting, lock_statistics)

基类:object

变量:
class anyio.CapacityLimiterStatistics(borrowed_tokens, total_tokens, borrowers, tasks_waiting)

基类:object

变量:
  • borrowed_tokens (int) -- number of tokens currently borrowed by tasks

  • total_tokens (float) -- total number of available tokens

  • borrowers (tuple) -- tasks or other objects currently holding tokens borrowed from this limiter

  • tasks_waiting (int) -- number of tasks waiting on acquire() or acquire_on_behalf_of()

class anyio.SemaphoreStatistics(tasks_waiting)

基类:object

变量:

tasks_waiting (int) -- number of tasks waiting on acquire()

操作系统信号

Operating system signals

anyio.open_signal_receiver(*signals)

Start receiving operating system signals.

参数:

signals (Signals) -- signals to receive (e.g. signal.SIGINT)

返回类型:

ContextManager[AsyncIterator[Signals]]

返回:

an asynchronous context manager for an asynchronous iterator which yields signal numbers

警告

Windows does not support signals natively so it is best to avoid relying on this in cross-platform applications.

警告

On asyncio, this permanently replaces any previous signal handler for the given signals, as set via add_signal_handler().

低级操作

Low level operations

async anyio.lowlevel.checkpoint()

Check for cancellation and allow the scheduler to switch to another task.

Equivalent to (but more efficient than):

await checkpoint_if_cancelled()
await cancel_shielded_checkpoint()
返回类型:

None

Added in version 3.0.

async anyio.lowlevel.checkpoint_if_cancelled()

Enter a checkpoint if the enclosing cancel scope has been cancelled.

This does not allow the scheduler to switch to a different task. :rtype: None

Added in version 3.0.

async anyio.lowlevel.cancel_shielded_checkpoint()

Allow the scheduler to switch to another task but without checking for cancellation.

Equivalent to (but potentially more efficient than):

with CancelScope(shield=True):
    await checkpoint()
返回类型:

None

Added in version 3.0.

class anyio.lowlevel.RunVar(name, default=_NoValueSet.NO_VALUE_SET)

基类:Generic[T]

Like a ContextVar, except scoped to the running event loop.

测试和调试

Testing and debugging

class anyio.TaskInfo(id, parent_id, name, coro)

基类:object

Represents an asynchronous task.

变量:
  • id (int) -- the unique identifier of the task

  • parent_id (Optional[int]) -- the identifier of the parent task, if any

  • name (str) -- the description of the task (if any)

  • coro (Coroutine) -- the coroutine object of the task

has_pending_cancellation()

Return True if the task has a cancellation pending, False otherwise.

返回类型:

bool

anyio.get_current_task()

Return the current task.

返回类型:

TaskInfo

返回:

a representation of the current task

anyio.get_running_tasks()

Return a list of running tasks in the current event loop.

返回类型:

list[TaskInfo]

返回:

a list of task info objects

async anyio.wait_all_tasks_blocked()

Wait until all other tasks are waiting for something.

返回类型:

None

异常

Exceptions

exception anyio.BrokenResourceError

基类:Exception

Raised when trying to use a resource that has been rendered unusable due to external causes (e.g. a send stream whose peer has disconnected).

exception anyio.BusyResourceError(action)

基类:Exception

Raised when two tasks are trying to read from or write to the same resource concurrently.

exception anyio.ClosedResourceError

基类:Exception

Raised when trying to use a resource that has been closed.

exception anyio.DelimiterNotFound(max_bytes)

基类:Exception

Raised during receive_until() if the maximum number of bytes has been read without the delimiter being found.

exception anyio.EndOfStream

基类:Exception

Raised when trying to read from a stream that has been closed from the other end.

exception anyio.IncompleteRead

基类:Exception

Raised during receive_exactly() or receive_until() if the connection is closed before the requested amount of bytes has been read.

exception anyio.TypedAttributeLookupError

基类:LookupError

Raised by extra() when the given typed attribute is not found and no default value has been given.

exception anyio.WouldBlock

基类:Exception

Raised by X_nowait functions if X() would block.