确保模块asynci中的未来不可用

2024-05-28 19:20:50 发布

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

我试图从python asyncio tasks & coroutines documentation运行这个示例

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的其他示例似乎也可以工作。

我尝试打开一个新的解释器会话并从asyncio导入ensure_future

from asyncio import ensure_future

我收到导入错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name 'ensure_future'

我可以访问另一台运行Ubuntu 14.04并安装了python 3.4.0的机器。我在那里试过同样的导入,不幸的是也遇到了同样的导入错误。

asyncio的api是否已经更改,并且没有在文档示例中反映出来,或者可能有一个错误,并确保文档中的函数应该是其他的东西?

这个例子对SO社区的其他成员有用吗?

谢谢。


Tags: from文档importloopasyncio示例def错误
1条回答
网友
1楼 · 发布于 2024-05-28 19:20:50

https://docs.python.org/3.4/library/asyncio-task.html#asyncio.ensure_future

asyncio.ensure_future(coro_or_future, *, loop=None)

Schedule the execution of a coroutine object: wrap it in a future. Return a Task object.

If the argument is a Future, it is returned directly.

New in version 3.4.4.

这就是“Who is to blame?”的意思。关于“What is to be done?”:

asyncio.async(coro_or_future, *, loop=None)

A deprecated alias to ensure_future().

Deprecated since version 3.4.4.

相关问题 更多 >

    热门问题