属性错误:模块“asyncio”没有属性“create\u task”

2024-04-19 12:39:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图asyncio.create_task()但我正在处理此错误:

下面是一个例子:

import asyncio
import time

async def async_say(delay, msg):
    await asyncio.sleep(delay)
    print(msg)

async def main():
    task1 = asyncio.create_task(async_say(4, 'hello'))
    task2 = asyncio.create_task(async_say(6, 'world'))

    print(f"started at {time.strftime('%X')}")
    await task1
    await task2
    print(f"finished at {time.strftime('%X')}")

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

输出:

AttributeError: module 'asyncio' has no attribute 'create_task'

所以我试着使用下面的代码片段(.ensure_future()),没有任何问题:

async def main():
    task1 = asyncio.ensure_future(async_say(4, 'hello'))
    task2 = asyncio.ensure_future(async_say(6, 'world'))

    print(f"started at {time.strftime('%X')}")
    await task1
    await task2
    print(f"finished at {time.strftime('%X')}")

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

输出:

started at 13:19:44
hello
world
finished at 13:19:50

怎么了?


[注意:

  • Python3.6
  • Ubuntu 16.04

[更新]:

借用@user4815162342Answer,我的问题解决了:

async def main():
    loop = asyncio.get_event_loop()
    task1 = loop.create_task(async_say(4, 'hello'))
    task2 = loop.create_task(async_say(6, 'world'))

    print(f"started at {time.strftime('%X')}")
    await task1
    await task2
    print(f"finished at {time.strftime('%X')}")

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

Tags: loopasynciotaskasynctimemaindefcreate
1条回答
网友
1楼 · 发布于 2024-04-19 12:39:58

^{}顶级函数是在Python 3.7中添加的,您正在使用python3.6。在3.7之前,create_task只能作为事件循环上的method使用,因此您可以这样调用它:

async def main():
    loop = asyncio.get_event_loop()
    task1 = loop.create_task(async_say(4, 'hello'))
    task2 = loop.create_task(async_say(6, 'world'))

这在3.6和3.7以及早期版本中都有效。^{}也可以工作,但是当你知道你在处理一个协程时,create_task更加明确,是preferred选项。

相关问题 更多 >