是肥宅SRP啊 发表于 2023-4-24 21:02:51

python协程问题

我是Windows系统,输入的代码如下,想问问该怎么解决这个问题呀
import asyncio

async def fun1():
    print('I am INsider1')
    await asyncio.sleep(1)
    print('1finished')

async def fun2():
    print("I am INsider2")
    await asyncio.sleep(2)
    print("2finished")

async def fun3():
    print("I am INsider3")
    await asyncio.sleep(3)
    print("3finished")

if __name__ == '__main__':
    f1 = fun1()
    f2 = fun2()
    f3 = fun3()

    fs =
    event_loop = asyncio.get_event_loop()
    event_loop.run_until_complete(asyncio.wait(fs))


报错如下:
    raise TypeError("Passing coroutines is forbidden, use tasks explicitly.")
TypeError: Passing coroutines is forbidden, use tasks explicitly.
sys:1: RuntimeWarning: coroutine 'fun1' was never awaited
sys:1: RuntimeWarning: coroutine 'fun2' was never awaited
sys:1: RuntimeWarning: coroutine 'fun3' was never awaited

isdkz 发表于 2023-4-24 21:02:52

从您的错误提示来看,问题出在您将协程函数直接传递给`asyncio.wait()`。解决这个问题的方法是使用`asyncio.create_task()`将协程函数包装为任务对象,然后传递这些任务对象给`asyncio.wait()`。请修改您的代码如下:

import asyncio

async def fun1():
    print('I am INsider1')
    await asyncio.sleep(1)
    print('1finished')

async def fun2():
    print("I am INsider2")
    await asyncio.sleep(2)
    print("2finished")

async def fun3():
    print("I am INsider3")
    await asyncio.sleep(3)
    print("3finished")

if __name__ == '__main__':
    f1 = fun1()
    f2 = fun2()
    f3 = fun3()

    fs =
   
    event_loop = asyncio.get_event_loop()
   
    # 将协程对象包装为任务对象
    tasks =

    # 将任务对象传递给 asyncio.wait
    event_loop.run_until_complete(asyncio.wait(tasks))


现在,您的代码应该可以正常运行并输出预期结果。另外,从Python 3.7开始,可以使用`asyncio.run()`简化事件循环的创建和关闭操作,不过这需要将您的代码封装在一个异步函数中。如果您的Python版本 >= 3.7,可以考虑将代码改成如下:

import asyncio

async def fun1():
    print('I am INsider1')
    await asyncio.sleep(1)
    print('1finished')

async def fun2():
    print("I am INsider2")
    await asyncio.sleep(2)
    print("2finished")

async def fun3():
    print("I am INsider3")
    await asyncio.sleep(3)
    print("3finished")

async def main():
    f1 = fun1()
    f2 = fun2()
    f3 = fun3()

    fs =
   
    tasks =
    await asyncio.wait(tasks)

if __name__ == '__main__':
    asyncio.run(main())


这样,代码会更简洁。
页: [1]
查看完整版本: python协程问题