我正在尝试从python asyncio任务和协程文档中运行此示例
import asyncio
@asyncio.coroutine
def slow_operation(future):
yield from asyncio.sleep(1)
future.set_result('Future is done!')
def got_result(future):
print(future.result())
loop.stop()
loop = asyncio.get_event_loop()
future = asyncio.Future()
asyncio.ensure_future(slow_operation(future))
future.add_done_callback(got_result)
try:
loop.run_forever()
finally:
loop.close()
但是,我收到此错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'ensure_future'
这行似乎让我感到悲伤:
asyncio.ensure_future(slow_operation(future))
我的python解释器是OSX Yosemite上的3.4.3,也是我上面链接到的文档的版本,我从中复制了该示例,因此,我不应该得到这个错误。这是我的python解释器的终端抓取:
Python 3.4.3 (default, Feb 25 2015, 21:28:45)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
页面中未引用的其他示例asyncio.ensure_future
似乎可行。
我尝试打开一个新的口译会话并ensure_future
从中导入asyncio
from asyncio import ensure_future
我收到导入错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'ensure_future'
我可以访问另一台运行安装了python 3.4.0的Ubuntu 14.04的计算机。我在那里尝试了相同的导入,但不幸的是遇到了相同的导入错误。
asyncio的api是否已更改,并且仅在文档示例中未得到反映,或者可能存在拼写错误,并且sure_function应该确实在文档中还有其他内容吗?
该示例对SO社区的其他成员有用(或无效)吗?
谢谢。
https://docs.python.org/3.4/library/asyncio-task.html#asyncio.ensure_future
asyncio.ensure_future(coro_or_future, *, loop=None)
安排协程对象的执行:在将来包装它。返回一个Task对象。
如果参数为
Future
,则直接返回。3.4.4版的新功能。
asyncio.async(coro_or_future, *, loop=None)
不推荐使用的别名
ensure_future().
从3.4.4版开始不推荐使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句