【问题标题】:AttributeError: module 'asyncio' has no attribute 'create_task'AttributeError:模块“asyncio”没有属性“create_task”
【发布时间】:2019-04-14 07:27:06
【问题描述】:

我正在尝试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'

所以我尝试使用以下代码 sn-p (.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

怎么了?


[注意]:

  • Python 3.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())

【问题讨论】:

    标签: python python-3.x async-await python-3.6 python-asyncio


    【解决方案1】:

    create_task 顶级函数是在 Python 3.7 中添加的,您使用的是 Python 3.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'))
        # ...
        await task1
        await task2
    

    这适用于 3.6 和 3.7 以及早期版本。 asyncio.ensure_future 也可以,但是当你知道你正在处理一个协程时,create_task 更明确并且是preferred 选项。

    【讨论】:

    • 感谢您的回答,但我遇到了这个错误:RuntimeWarning: coroutine 'main' was never awaited
    • @BenyaminJafari 请编辑问题以包含您正在测试的新代码。
    【解决方案2】:

    我喜欢这个

    if __name__ == '__main__':
            asyncio.get_event_loop().run_until_complete(scheduled(4))
    

    【讨论】:

    • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票。
    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 2018-04-14
    • 2019-02-18
    • 1970-01-01
    • 2020-01-01
    相关资源
    最近更新 更多