其他分享
首页 > 其他分享> > 异步中的奇怪AssertionError

异步中的奇怪AssertionError

作者:互联网

我正在尝试使用以下代码将超时标记为将来完成:

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设置Future时做错了吗?

解决方法:

导致异常的原因是:即使在future.set_result调用之后,greet仍继续运行;如果将True更改为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())

标签:python-3-x,python-asyncio,python
来源: https://codeday.me/bug/20191029/1960627.html