首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python: Coroutines StopIteration异常

Python: Coroutines StopIteration异常
EN

Stack Overflow用户
提问于 2018-12-26 05:43:35
回答 1查看 2K关注 0票数 0

我正试着用.send()来输入字典。下面是我的代码片段

代码语言:javascript
复制
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的异常。

代码语言:javascript
复制
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非常感谢您的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-26 08:33:52

你的协同线在第一次发送/屈服后就退出了。这将生成一个StopIteration,并且您不能在协同线本身中处理它,但只能在调用send时处理。从医生那里:

send()方法返回生成器产生的下一个值,如果生成器退出而不产生另一个值,则引发StopIteration。

代码语言:javascript
复制
@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

我想你想要保持协同线存活,接受任意数量的发送,直到一个显式的

代码语言:javascript
复制
@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异常。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53927889

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档