python异步编程asyncio教程
时间: 2025-01-09 07:47:52 浏览: 64
### Python `asyncio` 异步编程教程
#### 三、定义协程函数
在Python中,可以通过`async def`语句来定义一个协程函数。当调用这样的函数时,它并不会立即执行而是返回一个可以被等待完成的协程对象。
```python
async def my_coroutine():
await asyncio.sleep(1)
print("Coroutine executed")
```
此段代码展示了如何创建简单的协程函数[^4]。
#### 四、使用事件循环运行单个协程
为了启动并运行协程直到其结束,在最基础的情况下可以直接利用`asyncio.run()`方法传递要执行的任务给默认事件循环处理:
```python
import asyncio
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
print(f"started at {time.strftime('%X')}")
await say_after(1, 'hello')
await say_after(2, 'world')
print(f"finished at {time.strftime('%X')}")
# This line runs the event loop and waits until completion of all coroutines.
asyncio.run(main())
```
这段程序会依次打印时间戳以及'hello'和'world'[^1]。
#### 五、并发执行多个协程
如果希望同时发起几个独立的操作而不需要等到前一个完成后才开始下一个,则应该考虑采用更高级的方式如通过`gather()`收集所有待办事项作为一组任务一起提交给事件循环去调度它们之间的执行顺序:
```python
import asyncio
async def factorial(name, number):
f = 1
for i in range(2, number + 1):
print(f"Task {name}: Compute factorial({i})...")
await asyncio.sleep(1)
f *= i
print(f"Task {name}: factorial({number}) = {f}")
async def main():
# Schedule three calls *concurrently*:
await asyncio.gather(
factorial("A", 2),
factorial("B", 3),
factorial("C", 4),
)
await main()
```
上述例子说明了怎样让不同名称的任务并行计算阶乘值[^3]。
#### 六、设置超时期限
有时候可能需要限制某个操作的最大允许持续时间;这时就可以借助于`timeout()`辅助工具来做这件事儿——一旦超过指定的时间就会抛出异常终止该过程,并且还可以尝试调整已设定好的时限长度而不必重建整个环境配置.
```python
import asyncio
async def coroutine1():
await asyncio.sleep(5)
print('coroutine1 finished')
async def main():
try:
async with asyncio.timeout(1):
await coroutine1()
except TimeoutError as e:
print(e)
asyncio.run(main())
```
这里展示了一个带有超时机制的例子,其中任何未能及时完成的工作都会被捕获为特定类型的错误实例[^2]。
阅读全文
相关推荐


















