我试图用以下代码标记将来超时:
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())
"定时器" loop.call_later在3秒后将结果设置为future。它有效,但我也得到例外:
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完成的未来?
答案 0 :(得分:3)
导致异常的原因是: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())
答案 1 :(得分:1)
您不应该自己致电future.set_result()
。事件循环在任务返回后设置未来的结果。