python异步Trio大全实现既要又要还要
Trio 完整类与方法列表及导入方式
Trio 是 Python 中一个现代化的异步编程库,提供结构化并发、取消机制和清晰的错误处理。以下是按模块分类的核心组件列表及正确导入方式:
一、核心模块与导入方式
1. 主入口 (trio)
python
运行
import trio # 最常用的导入方式
# 核心函数
await trio.sleep(1) # 暂停执行1秒
trio.run(main) # 运行异步程序的主入口
await trio.gather(a(), b()) # 并发运行多个任务
# 取消与超时
with trio.move_on_after(5): # 5秒后自动取消
await long_running_task()
# 锁与同步原语
lock = trio.Lock() # 互斥锁
semaphore = trio.Semaphore(3) # 信号量,限制并发数
event = trio.Event() # 事件,用于任务间通知
condition = trio.Condition() # 条件变量
2. 结构化并发 (trio)
python
运行
# 核心类
async with trio.open_nursery() as nursery: # 管理一组子任务
nursery.start_soon(task1) # 启动异步任务
nursery.start_soon(task2, arg1, arg2) # 带参数的任务
# 任务组方法
nursery.cancel_scope # 获取当前取消范围
nursery.start_soon # 启动新任务
nursery.start_later # 安排稍后启动的任务
3. 取消机制 (trio.CancelScope)
python
运行
from trio import CancelScope
# 创建取消范围
with CancelScope() as scope:
await operation()
scope.cancel() # 手动取消范围内的所有任务
# 超时取消
with trio.move_on_after(10) as scope: # 10秒后自动取消
await slow_operation()
# 屏蔽取消
with trio.CancelScope(shield=True): # 屏蔽外部取消请求
await critical_section()
4. 通道 (trio.abc.SendChannel, trio.abc.ReceiveChannel)
python
运行
from trio import open_memory_channel
# 创建内存通道
send_channel, receive_channel = open_memory_channel(max_buffer_size=0)
# 发送端
await send_channel.send(data) # 发送数据
send_channel.close() # 关闭通道
# 接收端
async for value in receive_channel: # 异步迭代接收数据
process(value)
5. 同步原语
python
运行
# 锁
lock = trio.Lock()
async with lock: # 异步获取锁
await critical_operation()
# 信号量
semaphore = trio.Semaphore(5) # 最多允许5个并发
async with semaphore:
await limited_operation()
# 事件
event = trio.Event()
await event.wait() # 等待事件被设置
event.set() # 设置事件
# 条件变量
condition = trio.Condition()
async with condition:
await condition.wait() # 等待条件
condition.notify_all() # 通知所有等待者
6. 异步流 (trio.abc)
python
运行
# 网络流
from trio import open_tcp_stream, open_unix_socket
async with await open_tcp_stream(host, port) as stream:
await stream.send_all(data) # 发送数据
received = await stream.receive_some(1024) # 接收数据
# 文件IO流
from trio import open_file
async with await open_file("path.txt", "r") as f:
content = await f.read() # 异步读取文件
7. 异步文件操作 (trio)
python
运行
# 文件操作
from trio import open_file, Path
# 使用Path类(类似pathlib,但异步)
path = trio.Path("example.txt")
await path.write_text("Hello, Trio!") # 异步写入
content = await path.read_text() # 异步读取
# 传统文件API
async with await open_file("data.bin", "wb") as f:
await f.write(b"binary data")
8. 子进程 (trio)
python
运行
from trio import run_process
# 运行外部命令
result = await run_process(["ls", "-l"], capture_stdout=True)
print(result.stdout.decode()) # 输出命令结果
9. 测试工具 (trio.testing)
python
运行
from trio.testing import MockClock, assert_checkpoints
# 模拟时钟(用于测试)
async def test_with_mock_clock():
clock = MockClock()
await trio.testing.run_tests(clock=clock)
# 断言检查点(确保代码可取消)
async def test_checkpoints():
with assert_checkpoints():
await some_operation()
10. 底层 API (trio.lowlevel)
python
运行
from trio.lowlevel import start_guest_run, current_task
# 在现有事件循环中运行Trio(高级用法)
start_guest_run(
async_fn,
run_sync_soon_threadsafe=schedule_fn,
)
# 获取当前任务
task = current_task()
二、完整模块列表
以下是 Trio 主要模块的完整列表(不含所有子模块):
python
运行
# 核心模块
import trio
import trio.abc # 抽象基类
import trio.lowlevel # 底层API
import trio.testing # 测试工具
import trio.socket # 异步socket
import trio.subprocess # 异步子进程
import trio.hazmat # 危险/实验性API
# 同步原语
from trio import Lock, Semaphore, Event, Condition, CapacityLimiter
# 结构化并发
from trio import open_nursery, CancelScope, move_on_after, fail_after
# 通道
from trio import open_memory_channel, MemorySendChannel, MemoryReceiveChannel
# 异步流
from trio import open_tcp_stream, open_ssl_over_tcp_stream
from trio import open_unix_socket, SocketStream, SocketListener
from trio import open_file, Path
# 时钟与时间
from trio import current_time, sleep, sleep_forever
# 任务管理
from trio import current_task, current_root_task, spawn
# 测试工具
from trio.testing import MockClock, assert_checkpoints, wait_all_tasks_blocked
三、导入建议
-
按需导入:避免使用
from trio import *,而是明确导入需要的类或函数
python运行from trio import open_nursery, sleep # 推荐 -
使用别名:对于长模块名,可使用别名提高代码可读性
python运行import trio.lowlevel as lowlevel # 简化底层API访问 -
模块化组织:将相关导入放在一起,提高代码可维护性
python运行# 结构化并发 from trio import open_nursery, CancelScope, move_on_after # 同步原语 from trio import Lock, Event, Semaphore -
测试专用导入:在测试文件中单独导入测试工具
python运行# test_my_code.py from trio.testing import MockClock, assert_checkpoints
四、官方文档与资源
如需更详细的类和函数说明,建议查阅官方文档:
浙公网安备 33010602011771号