4

私はこのコードでタイムアウトによって未来をマークしようとしています:

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 秒後に結果を未来に設定します。動作しますが、例外も発生しています:

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 によって行われる未来の設定で何か間違ったことをしていますか?

4

2 に答える 2

3

例外の原因:呼び出しgreet後も引き続き実行されます。future.set_resultで変更するwhile Trueif 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())
于 2014-05-24T03:23:35.813 に答える
1

自称してはいけませんfuture.set_result()。イベント ループは、タスクが返された後に未来の結果を設定します。

于 2014-05-24T08:01:16.993 に答える