【发布时间】:2015-03-15 20:05:20
【问题描述】:
我很难理解协程是如何链接在一起的。在一个比 hello world 或 factorials 稍微不那么琐碎的例子中,我想要一个循环来持续监视文件修改时间,然后在文件被触摸时打印出时间:
#!/usr/bin/env python3
import os
import asyncio
@asyncio.coroutine
def pathmonitor(path):
modtime = os.path.getmtime(path)
while True:
new_time = os.path.getmtime(path)
if new_time != modtime:
modtime = new_time
yield modtime
yield from asyncio.sleep(1)
@asyncio.coroutine
def printer():
while True:
modtime = yield from pathmonitor('/home/users/gnr/tempfile')
print(modtime)
loop = asyncio.get_event_loop()
loop.run_until_complete(printer())
loop.run_forever()
我希望这可以工作 - 但是,当我运行它时,我得到:
RuntimeError: Task got bad yield: 1426449327.2590399
我在这里做错了什么?
更新:关于观察者模式的示例,请参阅下面的答案(即,在文件被触及时有效地允许多个注册者获取更新)而不使用回调(您必须使用任务)。
UPDATE2:有一个更好的解决方法:3.5 的async for(异步迭代器):https://www.python.org/dev/peps/pep-0492/
【问题讨论】:
标签: python python-3.x python-asyncio