【问题标题】:Strange AssertionError in asyncio异步中的奇怪 AssertionError
【发布时间】:2014-05-24 02:58:13
【问题描述】:

我正在尝试使用此代码通过超时标记未来完成:

import asyncio


@asyncio.coroutine
def greet():
    while True:
        print('Hello World')
        yield from asyncio.sleep(1)

@asyncio.coroutine
def main():
    future = asyncio.async(greet())
    loop.call_later(3, lambda: future.set_result(True))
    yield from future
    print('Ready')

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

"Timer" loop.call_later 将结果设置为 3 秒后的未来。它有效,但我也遇到了异常:

Hello World
Hello World
Hello World
Ready
Exception in callback <bound method Task._wakeup of Task(<greet>)<result=True>>(Future<result=None>,)
handle: Handle(<bound method Task._wakeup of Task(<greet>)<result=True>>, (Future<result=None>,))
Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\asyncio\events.py", line 39, in _run
    self._callback(*self._args)
  File "C:\Python33\lib\site-packages\asyncio\tasks.py", line 337, in _wakeup
    self._step(value, None)
  File "C:\Python33\lib\site-packages\asyncio\tasks.py", line 267, in _step
    '_step(): already done: {!r}, {!r}, {!r}'.format(self, value, exc)
AssertionError: _step(): already done: Task(<greet>)<result=True>, None, None

这个 AssertionError 是什么意思?我做错了什么设置由 loop.call_later 完成的未来?

【问题讨论】:

    标签: python python-3.x python-asyncio


    【解决方案1】:

    导致异常的原因:greet 即使在future.set_result 调用之后仍继续运行;通过将while True 更改为if True,您就会明白我的意思。

    asyncio.Event怎么样?

    import asyncio
    
    
    @asyncio.coroutine
    def greet(stop):
        while not stop.is_set():
            print('Hello World')
            yield from asyncio.sleep(1)
    
    
    @asyncio.coroutine
    def main():
        stop = asyncio.Event()
        loop.call_later(3, stop.set)
        yield from asyncio.async(greet(stop))
        print('Ready')
    
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    

    【讨论】:

      【解决方案2】:

      你不应该自己打电话给future.set_result()。事件循环在任务返回后设置future的结果。

      【讨论】:

        猜你喜欢
        • 2018-08-14
        • 1970-01-01
        • 1970-01-01
        • 2021-04-01
        • 1970-01-01
        • 2012-08-17
        • 2015-12-29
        • 1970-01-01
        • 2020-07-28
        相关资源
        最近更新 更多