【发布时间】:2016-03-04 09:42:28
【问题描述】:
我有一些使用 Python 3.4 的 asyncio 使用 call_later 编写的简单代码。代码应该打印,等待 10 秒,然后再次打印(而是在应该执行 end() 时引发 TypeError,见下文):
import asyncio
@asyncio.coroutine
def begin():
print("Starting to wait.")
asyncio.get_event_loop().call_later(10, end())
@asyncio.coroutine
def end():
print("completed")
if __name__ == "__main__":
try:
loop = asyncio.get_event_loop()
loop.create_task(begin())
loop.run_forever()
except KeyboardInterrupt:
print("Goodbye!")
给出错误:
Exception in callback <generator object coro at 0x7fc88eeaddc8>()
handle: <TimerHandle when=31677.188005054 <generator object coro at 0x7fc88eeaddc8>()>
Traceback (most recent call last):
File "/usr/lib64/python3.4/asyncio/events.py", line 119, in _run
self._callback(*self._args)
TypeError: 'generator' object is not callable
据我从文档 (https://docs.python.org/3/library/asyncio-task.html#coroutine) 中得知,call_later 采用协程对象,该对象是通过调用协程函数获得的。这似乎是我所做的,但 asyncio 没有正确调用 end()。
这应该怎么做?
【问题讨论】:
标签: python python-asyncio