asyncio 是 Python 3.4 引入的一个用于编写单线程并发代码的库。它使用协程(coroutine)来实现异步 I/O 操作,从而避免了传统的多线程或多进程带来的复杂性和开销。以下是使用 asyncio 进行异步编程的基本步骤和示例:
1. 定义协程
协程使用 async def 关键字定义,函数内部可以使用 await 关键字来等待其他协程的完成。
python复制代码
import asyncio | |
async def say_hello(): | |
print("Hello, World!") | |
await asyncio.sleep(1) # 模拟 I/O 操作,如网络请求或文件读写 | |
print("Hello again!") |
2. 运行协程
协程对象本身不会自动运行,需要通过事件循环(event loop)来调度和执行。
python复制代码
# 获取事件循环 | |
loop = asyncio.get_event_loop() | |
# 运行协程(在 Python 3.7+ 中,可以使用 asyncio.run()) | |
try: | |
loop.run_until_complete(say_hello()) | |
finally: | |
loop.close() |
或者在 Python 3.7 及以上版本,可以直接使用 asyncio.run():
python复制代码
asyncio.run(say_hello()) |
3. 并行运行多个协程
使用 asyncio.gather() 可以并行运行多个协程,并等待它们全部完成。
python复制代码
async def say_hello(name): | |
print(f"Hello, {name}!") | |
await asyncio.sleep(1) | |
print(f"Hello again, {name}!") | |
async def main(): | |
await asyncio.gather( | |
say_hello("Alice"), | |
say_hello("Bob"), | |
say_hello("Charlie") | |
) | |
# 运行主协程 | |
asyncio.run(main()) |
4. 处理异步任务
asyncio.create_task() 可以显式地创建一个任务(Task),任务也是一个协程对象,可以被调度和执行。
python复制代码
async def say_hello(name): | |
print(f"Hello, {name}!") | |
await asyncio.sleep(1) | |
print(f"Hello again, {name}!") | |
async def main(): | |
task1 = asyncio.create_task(say_hello("Alice")) | |
task2 = asyncio.create_task(say_hello("Bob")) | |
# 等待所有任务完成 | |
await task1 | |
await task2 | |
# 运行主协程 | |
asyncio.run(main()) |
5. 异步上下文管理器
可以使用 async with 语句来管理异步上下文,例如异步文件操作或数据库连接。
python复制代码
import asyncio | |
class MyContextManager: | |
async def __aenter__(self): | |
print("Entering context") | |
return self | |
async def __aexit__(self, exc_type, exc_val, exc_tb): | |
print("Exiting context") | |
async def main(): | |
async with MyContextManager() as cm: | |
print("Inside context") | |
await asyncio.sleep(1) | |
# 运行主协程 | |
asyncio.run(main()) |
6. 使用异步库
许多第三方库也提供了异步支持,例如 aiohttp 用于异步 HTTP 请求,aiomysql 用于异步数据库操作。以下是一个使用 aiohttp 发送 GET 请求的示例:
python复制代码
import aiohttp | |
import asyncio | |
async def fetch(session, url): | |
async with session.get(url) as response: | |
return await response.text() | |
async def main(): | |
async with aiohttp.ClientSession() as session: | |
html = await fetch(session, 'http://example.com') | |
print(html) | |
# 运行主协程 | |
asyncio.run(main()) |
这些示例展示了如何使用 asyncio 进行基本的异步编程。掌握这些概念后,你可以构建更复杂和高效的异步应用程序。
488

被折叠的 条评论
为什么被折叠?



