import asyncio import time async def func1(): print('这是aaa') await asyncio.sleep(3) print('这是aaa') async def func2(): print('这是bbb') await asyncio.sleep(2) print('这是bbb') async def func3(): print('这是ccc') await asyncio.sleep(4) print('这是ccc') if __name__ == '__main__': f1 = func1() f2 = func2() f3 = func3() tasks = [f1, f2, f3] t1 = time.time() asyncio.run(asyncio.wait(tasks)) t2 = time.time() print(t2-t1) 请问我的Python是目前官方最新版本,为什么我这种异步写法的代码会报错, 错误为TypeError: Passing coroutines is forbidden, use tasks explicitly.
时间: 2024-03-10 08:47:45 浏览: 168
这是因为最新版的Python已经不允许直接将协程对象传递给asyncio.wait()函数,需要将协程对象转换成任务对象。可以使用asyncio.create_task()函数将协程对象转换成任务对象,然后将任务对象加入到任务列表中即可。修改后的代码如下:
```python
import asyncio
import time
async def func1():
print('这是aaa')
await asyncio.sleep(3)
print('这是aaa')
async def func2():
print('这是bbb')
await asyncio.sleep(2)
print('这是bbb')
async def func3():
print('这是ccc')
await asyncio.sleep(4)
print('这是ccc')
if __name__ == '__main__':
f1 = asyncio.create_task(func1())
f2 = asyncio.create_task(func2())
f3 = asyncio.create_task(func3())
tasks = [f1, f2, f3]
t1 = time.time()
asyncio.run(asyncio.wait(tasks))
t2 = time.time()
print(t2-t1)
```
这样就可以正常运行了。
阅读全文