python的异步io代码正确但依旧运行错误

为啥会出现这样的错误代码没有问题呀


async def f1():
    print('f1 start', current_thread())
    await asyncio.sleep(1)
    print('f1 end', current_thread())


async def f2():
    print('f2 start', current_thread())
    data = await asyncio.sleep(1)
    print('结果', data)
    print('f2 end', current_thread())


tasks = [f1(), f2()]
loop = asyncio.get_event_loop()    # 产生(获取)一个事件循环
loop.run_until_complete(asyncio.wait(tasks))


Traceback (most recent call last):
  File "E:\wgt python\网络编程\32-异步IO.py", line 65, in <module>
    loop.run_until_complete(asyncio.wait(tasks))
  File "C:\Users\r9000p\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\r9000p\AppData\Local\Programs\Python\Python311\Lib\asyncio\tasks.py", line 415, in wait
    raise TypeError("Passing coroutines is forbidden, use tasks explicitly.")
TypeError: Passing coroutines is forbidden, use tasks explicitly.
sys:1: RuntimeWarning: coroutine 'f2' was never awaited
sys:1: RuntimeWarning: coroutine 'f1' was never awaited

【以下回答由 GPT 生成】

问题分析:

根据错误提示,代码中的协程(f1和f2)没有被正确地await,导致了报错。此外,还有另一个问题是在创建任务列表时,应该传入协程对象而不是直接调用协程函数。

解决方案:

  1. 首先,将协程函数调用改为协程对象。
  2. 其次,确保每个协程对象都被正确地await。
  3. 最后,使用asyncio的gather()方法来运行所有的协程任务。

下面是修改后的代码:

import asyncio
from threading import current_thread

async def f1():
    print('f1 start', current_thread())
    await asyncio.sleep(1)
    print('f1 end', current_thread())


async def f2():
    print('f2 start', current_thread())
    data = await asyncio.sleep(1)
    print('结果', data)
    print('f2 end', current_thread())


# 创建协程对象
task1 = f1()
task2 = f2()

# 使用gather()方法运行协程任务
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(task1, task2))

请注意,在修改后的代码中,我们将协程函数调用的结果赋值给了变量task1task2,然后将这些协程对象传递给了gather()方法。

这样,代码应该不再出现之前的问题,并且正确运行。

希望这个解决方案对你有帮助!如果你还有其他问题,请随时提问。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^