【问题标题】:does merry handle exceptions in python?快乐处理python中的异常吗?
【发布时间】:2018-03-28 12:39:05
【问题描述】:

我一直在寻找更多pythonic方法来处理python中的错误,我发现merry

如果您从未听说过,这里是文档:https://github.com/miguelgrinberg/merry

所以我用merry写了一个小代码

from merry import Merry

merry = Merry()

@merry._try
def write_to_file(filename,data):
    with open(filename,'w') as file_obj:
        file_obj.write(data) 

@merry._except(FileNotFoundError)
def fileNotFoundError():
    print("File not found")

@merry._except(Exception)
def catch_all(e):
    print(f"exception occured :{e}")

@merry._else
def else_clause():
    print("no exceptions occured")

path = "C:/Users/User/Desktop1/dataHere.txt"
text = "top secret information"

write_to_file(path,text)     

请注意,我改变了提高的路径

文件未找到错误

我以为 merry 会处理错误,但我得到了以下输出:

[快乐] 捕获异常

Traceback(最近一次调用最后一次):文件 “C:\python36\lib\site-packages\merry.py”,第 26 行,在包装器中 ret = f(*args, **kwargs) 文件“C:/Users/User/Desktop/merrymerry.py”,第 7 行,在 write_to_file 使用 open(filename,'w') as file_obj: FileNotFoundError: [Errno 2] 没有这样的文件或目录: 'C:/Users/j.sinjaradze/Desktop1/dataHere.txt' 找不到文件

是不是我做错了什么,或者只是快乐没有像我预期的那样工作?

【问题讨论】:

    标签: python python-3.x exception merry


    【解决方案1】:

    我认为您误解了您的输出/merry 的工作原理。在您的输出中,您有:

    [merry] Exception caught
    

    表示merry捕获了异常。然后是异常的回溯,默认是merry输出,然后是

    File not found
    

    这是你的结果

    def fileNotFoundError():
        print("File not found")
    

    所以一切正常

    附录。为什么merry会输出异常?

    在merry的源码中(见你链接的github),有这行(merry.py:46):

    self.logger.exception('[merry] Exception caught')
    

    self.logger 先前是从 logging.getLogger(logger_name) 调用创建的,异常函数会打印附加到先前发生的异常的回溯的消息(有关详细信息,请参阅 python logging documentation)。

    从源代码中,如果不触及 merry.py 的源代码,我看不到改变这种行为的方法

    【讨论】:

    • 感谢回答^_^,但不明白为什么会显示回溯?
    • @FlyingTeller 您可以访问记录器 (github.com/miguelgrinberg/merry#logging) 并更改其级别或添加过滤器。无需更改来源。
    猜你喜欢
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    相关资源
    最近更新 更多