gpt4 book ai didi

python - 如何让python优雅地失败?

转载 作者:太空狗 更新时间:2023-10-29 17:10:28 24 4
gpt4 key购买 nike

我只是想知道如何让 python 在所有可能的错误中以用户定义的方式失败。

例如,我正在编写一个处理(大)项目列表的程序,其中一些项目可能不是我定义的格式。如果 python 检测到错误,它目前只会吐出一条丑陋的错误消息并停止整个过程。但是,我希望它只是将错误与一些上下文一起输出到某个地方,然后继续进行下一项。

如果有人能帮我解决这个问题,我将不胜感激!

非常感谢!

杰森

最佳答案

以下是我在复杂脚本和中型应用程序中经常使用的一些基本策略。

提示 1:在继续处理有意义的每个级别捕获错误。在您的情况下,它可能在循环内部。您不必保护每一行或每个函数调用,而只需保护在错误中幸存下来的地方。

提示 2:使用日志记录模块以可配置的方式报告发生的事情,独立于您在大型应用程序中将模块与其他模块组合的方式。开始在您的模块中导入根记录器,然后在几个不同的地方使用它,您最终可能会找到一个更合理的日志记录层次结构。

import logging
logger = logging.getLogger()

for item in items:
try:
process(item)
except Exception, exc:
logger.warn("error while processing item: %s", exc)

技巧 3:定义“应用程序异常”,最终您可能想要定义此类异常的层次结构,但在需要时最好发现这一点。当您处理的数据不是您所期望的或表示不一致的情况时,使用此类异常“冒出”,同时将它们与正常的标准异常分开,这些异常是由常规错误或建模域外的问题(IO 错误)引起的等)。

class DomainException(Exception):
"""Life is not what I expected"""

def process(item):
# There is no way that this item can be processed, so bail out quickly.
# Here you are assuming that your caller will report this error but probably
# it will be able to process the other items.
if item.foo > item.bar:
raise DomainException("bad news")

# Everybody knows that every item has more that 10 wickets, so
# the following instruction is assumed always being successful.
# But even if luck is not on our side, our caller will be able to
# cope with this situation and keep on working
item.wickets[10] *= 2

主要功能是最外面的检查点:最终在这里处理您的任务完成的可能方式。如果这不是 shell 脚本(而是例如 UI 应用程序中对话框下的处理或 web 应用程序中 POST 后的操作),只有报告错误的方式会发生变化(并且日志记录方法的使用完全分离了实现从其界面进行处理)。

def main():
try:
do_all_the_processing()
return 0
except DomainException, exc:
logger.error("I couldn't finish. The reason is: %s", exc)
return 1
except Exception, exc:
logger.error("Unexpected error: %s - %s", exc.__class__.__name__, exc)
# In this case you may want to forward a stacktrace to the developers via e-mail
return 1
except BaseException:
logger.info("user stop") # this deals with a ctrl-c
return 1

if __name__ == '__main__':
sys.exit(main())

关于python - 如何让python优雅地失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/497952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com