Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/drupal/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python asyncio中奇怪的断言错误_Python_Python 3.x_Python Asyncio - Fatal编程技术网

Python asyncio中奇怪的断言错误

Python asyncio中奇怪的断言错误,python,python-3.x,python-asyncio,Python,Python 3.x,Python Asyncio,我正试图用以下代码通过超时标记将来完成: 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:

我正试图用以下代码通过超时标记将来完成:

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_稍后会在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
你好,世界
你好,世界
你好,世界
准备好的
回调中的异常(将来,)
句柄:句柄(,(未来,))
回溯(最近一次呼叫最后一次):
文件“C:\Python33\lib\site packages\asyncio\events.py”,第39行,正在运行
self.\u回调(*self.\u参数)
文件“C:\Python33\lib\site packages\asyncio\tasks.py”,第337行,在_wakeup中
自身步骤(值,无)
文件“C:\Python33\lib\site packages\asyncio\tasks.py”,第267行,步骤
“_step():已完成:{!r},{!r},{!r}”。格式(self,value,exc)
断言错误:_步骤():已完成:任务(),无,无

这个断言错误是什么意思?我是否在通过循环设置future done by loop时出错。请稍后调用?

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

使用如何


你不应该自己调用
future.set\u result()
。事件循环设置任务返回后的未来结果

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())