chaining coroutines in asyncio (and observer pattern)(在异步(和观察者模式)中链接协程)
本文介绍了在异步(和观察者模式)中链接协程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很难理解协程是如何链接在一起的。在一个比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/
推荐答案
我在链接的协程中使用return而不是yield使您的代码正常工作,就像chained coroutines example:
#!/usr/bin/env python3
import os
import asyncio2
@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
return modtime
yield from asyncio.sleep(1)
@asyncio.coroutine
def printer():
while True:
modtime = yield from pathmonitor('/tmp/foo.txt')
print(modtime)
loop = asyncio.get_event_loop()
loop.run_until_complete(printer())
loop.run_forever()
请注意,printer()的循环将为每个迭代创建一个新的pathmonitor生成器。不确定这是否是您想要的生成器,但这可能是一个开始。
我自己觉得协程API和语法有点混乱。以下是我觉得有帮助的一些读物:
- What’s New In Python 3.3: "PEP 380: Syntax for Delegating to a Subgenerator"
- PEP380: "Formal semantics"
- asyncio: "Example: Chain coroutines"
- Greg Ewing's "Binary Tree" example
这篇关于在异步(和观察者模式)中链接协程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:在异步(和观察者模式)中链接协程
基础教程推荐
猜你喜欢
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
