每个循环只打印一次错误信息

0 投票
2 回答
714 浏览
提问于 2025-04-18 18:30

我有一些Python代码,长得像这样:

for row in reader:
    if # something
       # do things
    else:
        try:
            # do more things
        except IndexError:
            logger.info('message')

结果是,我在每次循环的时候都会看到一大堆输出,上面写着 INFO:...message。这没必要出现超过1000次。离开循环后,我可以用一个“标志”来处理这个问题,像这样:

for row in reader
    # if/else/try
        except IndexError:
            foo = True
if foo:
    logger.info('message')

不过我在想,是否有更优雅的办法来解决这个问题。重要的是,我确实想显示错误信息,但只想显示一次。而且我不能因为错误就跳出循环,因为我还需要继续处理 reader 中的其他 rowIndexError 错误是在我尝试从一个可能不存在的列表中创建变量时出现的。我必须这样做,因为如果变量不存在,我需要跳过它,而不是提供一个空值。

所以我就陷入了这个奇怪的困境。有没有更好的解决办法呢?最好是最“Pythonic”的方式,因为在这种情况下,速度什么的并不是特别重要。

2 个回答

0

你可以在这里使用警告模块。通过使用警告过滤器,https://docs.python.org/3/library/warnings.html#temporarily-suppressing-warnings,你可以让警告只显示一次。

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("once")
    fxn()
1

只需要保持一个计数器,有时候最简单的方法就是最好的。你甚至可以在最后加一个很酷的提示。

bad = 0
for row in reader:
    if # something
       # do things
    else:
        try:
            # do more things
        except IndexError:
            bad += 1
            if bad == 1:
                logger.info('message')
if bad:
    logger.info('%d bad things happened' % bad)

撰写回答