AttributeError:模块“ asyncio”没有属性“ create_task”

时间:2018-11-11 09:50:49

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

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

[更新]:

通过@@ user4815162342 answer的借阅,我更新了我的问题:

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 3.6
  • Ubuntu 16.04

2 个答案:

答案 0 :(得分:9)

在Python 3.7中添加了create_task顶级函数,并且您正在使用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'))

在3.6和3.7以及早期版本中均可使用。 asyncio.ensure_future也可以使用,但是当您知道要使用协同程序时,create_task更为明确,是preferred选项。

答案 1 :(得分:0)

我喜欢这个

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