【问题标题】:Capture StopIteration Error Message in For Loop在 For 循环中捕获 StopIteration 错误消息
【发布时间】:2015-11-20 23:50:18
【问题描述】:

我有类似这种结构的代码:

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

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

谢谢

【问题讨论】:

  • 为什么不提出像ValueError 这样的不同类型的错误呢?这样你就可以做一个try .. except ValueError: ..
  • @hgwells 在你提到它之前不久我就想到了。再想一想,我找不到不按照你的建议做的理由。不知道我现在是否应该删除问题。
  • yield 的元组似乎缺少第二个值。 else 分支可以是单行:return (p.split() for p in parse_my_string(some_str))
  • @BlackJack 缺失值是错字。谢谢。其余的代码被缩短只是为了理解这一点。实际代码有点长。

标签: python exception exception-handling generator stopiteration


【解决方案1】:

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

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

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

print('Done')

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-03
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    相关资源
    最近更新 更多