Python 使用 future 和loop_forever

标签 python python-3.x python-asyncio

刚刚开始尝试异步,看起来真的很酷。我尝试将 future 与永远运行的异步协程一起使用,但出现此错误:

Task exception was never retrieved
future: <Task finished coro=<slow_operation() done, defined at ./asynchio-test3.py:5> exception=InvalidStateError("FINISHED: <Future finished result='This is the future!'>",)>

这是我的代码,如果我删除与 futures 相关的 3 行,它会按预期运行:

import asyncio

@asyncio.coroutine
def slow_operation():
    yield from asyncio.sleep(1)
    print ("This is the task!")
    future.set_result('This is the future!')
    asyncio.async(slow_operation())

def got_result(future):
    print(future.result())

loop = asyncio.get_event_loop()
future = asyncio.Future()
future.add_done_callback(got_result)
asyncio.async(slow_operation())
try:
    loop.run_forever()
finally:
    loop.close()

最佳答案

slow_operator 无限期调用,调用 set_result多次针对同一个 future 对象;这是不可能的。

>>> import asyncio
>>> future = asyncio.Future()
>>> future.set_result('result')
>>> future.set_result('result')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python35\lib\asyncio\futures.py", line 329, in set_result
    raise InvalidStateError('{}: {!r}'.format(self._state, self))
asyncio.futures.InvalidStateError: FINISHED: <Future finished result='result'>

为每个 slow_operator 调用创建新的 future。例如:

@asyncio.coroutine
def slow_operation(future):
    yield from asyncio.sleep(1)
    print ("This is the task!")
    future.set_result('This is the future!')
    asyncio.async(slow_operation(new_future()))

def got_result(future):
    print(future.result())

def new_future():
    future = asyncio.Future()
    future.add_done_callback(got_result)
    return future

loop = asyncio.get_event_loop()
asyncio.async(slow_operation(new_future()))
try:
    loop.run_forever()
finally:
    loop.close()

顺便说一句,如果您使用的是 Python 3.5+,则可以使用新语法(asyncawait):

async def slow_operation(future):
    await asyncio.sleep(1)
    print ("This is the task!")
    future.set_result('This is the future!')
    asyncio.ensure_future(slow_operation(new_future()))

关于Python 使用 future 和loop_forever,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38161271/

相关文章:

python - "yield from"语法在 asyncio 中有什么作用,它与 "await"有何不同

python - 如何修复来自数据库的 Python 请求/BeautifulSoup 响应

python - 希望解决在本地主机上运行的 Google Plus API 命令行 Python 入门工具包中的 SSL 错误

python - Python 中的实时倒计时器

python - 在 django 中处理零行时 filter().update() 的最佳方法?

python - 如何在 Python 中调试卡住的 asyncio 协程?

python - 增强同步软件 API 以允许异步消费

python - 解析配置文件、环境和命令行参数,以获取单个选项集合

python-3.x - 按 ID 分组,同时保留所有数据。 Python。 Pandas

python-3.x - 如何在 f 字符串中使用 lambda 函数并有条件地返回值?