在 For 循环中捕获 StopIteration 错误消息

Mo2*_*Mo2 1 python exception generator stopiteration

我有类似于此结构的代码:

def my_gen(some_str):
    if some_str == "":
        raise StopIteration("Input was empty")
    else:
        parsed_list = parse_my_string(some_str)
        for p in parsed_list:
            x, y = p.split()
            yield x, y

for x, y in my_gen()
    # do stuff
    # I want to capture the error message from StopIteration if it was raised manually
Run Code Online (Sandbox Code Playgroud)

是否可以通过使用 for 循环来做到这一点?我在其他地方找不到类似的案例。如果无法使用 for 循环,还有哪些其他替代方案?

谢谢

Bur*_*lid 5

您不能在 for 循环中执行此操作 - 因为 for 循环将隐式捕获 StopIteration 异常。

一种可能的方法是使用无限的 while:

while True:
    try:
        obj = next(my_gen)
    except StopIteration:
        break

print('Done')
Run Code Online (Sandbox Code Playgroud)

或者您可以使用itertools 库中任意数量的使用者- 请查看底部的配方部分以获取示例。