gpt4 book ai didi

python - 属性错误 : module 'asyncio' has no attribute 'create_task'

转载 作者:太空狗 更新时间:2023-10-29 20:19:28 30 4
gpt4 key购买 nike

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

怎么了?


[注意]:

  • Python 3.6
  • Ubuntu 16.04

[更新]:

借自 @ 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())

最佳答案

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选项。

关于python - 属性错误 : module 'asyncio' has no attribute 'create_task' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53247533/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com