ensure_future not available in module asyncio

2019-02-12 16:22发布

问题:

I'm trying to run this example from the 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()

However, I get this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'ensure_future'

This is the line that seems to be causing me grief:

asyncio.ensure_future(slow_operation(future))

My python interpreter is 3.4.3 on OSX Yosemite, as is the version of documentation I linked to above, from which I copied the example, so I shouldn't be getting this errror. Here's a terminal-grab of my python interpreter:

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.

Other examples from the page not referencing asyncio.ensure_future seem to work.

I tried opening a fresh interpreter session and importing ensure_future from asyncio

from asyncio import ensure_future

I get an import error:

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

I have access to another machine running Ubuntu 14.04 with python 3.4.0 installed. I tried the same import there, and unfortunately faced the same import error.

Has the api for asyncio been changed and its just not reflected in the documentation examples, or maybe there's a typo and ensure_function should really be something else in the documentation?

Does the example work (or break) for other members of the SO community?

Thanks.

回答1:

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.

That's about it for "Who is to blame?". And regarding "What is to be done?":

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

A deprecated alias to ensure_future().

Deprecated since version 3.4.4.