简体   繁体   English

Python:协程-StopIteration异常

[英]Python: Coroutines - StopIteration exception

I am trying to feed a dictionary by using .send() . 我正在尝试使用.send()来喂字典。 And my code snippet is below 我的代码段如下

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()

And I believe I am handling the exception properly but still I am getting StopIteration exception. 而且我相信我可以正确处理该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

Am I not handling that exception properly or am I missing something ? 我是否无法正确处理该异常,还是缺少某些内容? ANy help greatly appreciated. 非常感谢您的帮助。

Your coroutine exits after first send/yield. 您的协程在首次发送/屈服后退出。 That generates a StopIteration and you cannot handle it in the coroutine itself, but only when invoking send . 这会生成一个StopIteration ,您不能在协程本身中处理它,而只能在调用send From the docs: 从文档:

The send() method returns the next value yielded by the generator, or raises StopIteration if the generator exits without yielding another value. 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

I guess you want to keep the coroutine alive accepting as many sends as you want until an explicit close : 我猜想您要使协程保持活动状态,直到显式关闭为止,您可以接受尽可能多的发送:

@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")

Please note that now the GeneratorExit exception is caught. 请注意,现在捕获了GeneratorExit异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM