我正试着用.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我是没有正确处理这个例外,还是遗漏了什么?ANy非常感谢您的帮助。
发布于 2018-12-26 08:33:52
你的协同线在第一次发送/屈服后就退出了。这将生成一个StopIteration,并且您不能在协同线本身中处理它,但只能在调用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异常。
https://stackoverflow.com/questions/53927889
复制相似问题