python - Python:协程 - StopIteration 异常
问题描述
我正在尝试使用.send()
. 我的代码片段如下
def coroutine(func):
def start(*args, **kwargs):
cr = func(*args, **kwargs)
next(cr)
return cr
return start
@coroutine
def putd(di):
print("via coroutines adding a key : value to dictionary")
try:
item = yield
for key, value in item.items():
if key in di:
print("Key : {0} already exists".format(key))
else:
di[key] = value
print(di)
except StopIteration :
print("yield frame got closed")
di = {}
gobj = putd(di)
gobj.send({"plan" : "shuttle"})
gobj.close()
而且我相信我处理exception
得当,但我仍然遇到StopIteration
异常。
scratch.py
Traceback (most recent call last):
via coroutines adding a key : value to dictionary
{'plan': 'shuttle'}
File "scratch.py", line 39, in <module>
gobj.send({"plan" : "shuttle"})
StopIteration
Process finished with exit code 1
我没有正确处理该异常还是我遗漏了什么?非常感谢任何帮助。
解决方案
您的协程在第一次发送/屈服后退出。这会生成 aStopIteration
并且您无法在协程本身中处理它,但只能在调用send
. 从文档:
send() 方法返回生成器产生的下一个值,或者如果生成器退出而没有产生另一个值,则引发 StopIteration。
@coroutine
def putd(di):
print("via coroutines adding a key : value to dictionary")
try:
item = yield
for key, value in item.items():
if key in di:
print("Key : {0} already exists".format(key))
else:
di[key] = value
print(di)
except StopIteration :
print("yield frame got closed")
# here is an implicit return None which terminates the coroutine
我想你想让协程保持活动状态,接受尽可能多的发送,直到显式关闭:
@coroutine
def putd(di):
print("via coroutines adding a key : value to dictionary")
try:
while True:
item = yield
for key, value in item.items():
if key in di:
print("Key : {0} already exists".format(key))
else:
di[key] = value
print(di)
except GeneratorExit:
print("yield frame got closed")
请注意,现在GeneratorExit
异常已被捕获。
推荐阅读
- pdb - 使用 MDAnalysis 从 pdb 中提取数组中的坐标
- svelte - 我应该如何使用汇总构建两个苗条页面?
- swiftui - 动画突然结束。我怎样才能使这个顺利?
- apache-spark - Azure Databricks:从 azure blob 存储中查找 databricks 增量表使用的文件
- php - 如何将默认的 php 代码重写为有效的回显行输出?
- iframe - 从安全角度将小部件嵌入网页的最佳实践
- keycloak - Keycloak - 基于资源的角色和范围基本身份验证
- html - 模板检查未发生/更改检测器未运行(角度)
- python - 保存为 pdf 时的 hist2d 条纹
- java - 如何在单元测试中使用不同的静态内容?