我正在尝试使用.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
我没有正确处理该异常还是我遗漏了什么?非常感谢任何帮助。