如何在python中的try except循环之前记录错误?

2024-03-28 10:08:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试实现Python的日志库。在

我知道如果在try-catch循环中包装了某些内容,则会捕获异常。在

但是在我的一个例子中,导入失败,这是脚本的开始。这不会被记录。(它只在朱皮特的日志中打印这个)

如何记录这些异常?寻找不包装在try-except循环中的整个脚本。在

Jupyter或任何IDE上的任何错误都会在控制台中打印出来,为什么不使用logger呢?难道没有这样的实现吗


Tags: 脚本内容错误记录jupyterloggeride例子
2条回答

使用logger时,您必须实现错误的日志记录。
在Python中,默认情况下,错误只记录到控制台。
所以,如果您想使用logger,就必须添加逻辑来捕获和记录错误。在

try except块是在Python上处理导入的常用方法。在

引用Dive into Python

There are a lot of other uses for exceptions besides handling actual error conditions. A common use in the standard Python library is to try to import a module, and then check whether it worked. Importing a module that does not exist will raise an ImportError exception. You can use this to define multiple levels of functionality based on which modules are available at run-time, or to support multiple platforms (where platform-specific code is separated into different modules).

The next example demonstrates how to use an exception to support platform-specific functionality.

try:
    import termios, TERMIOS                     
except ImportError:
    try:
        import msvcrt                           
    except ImportError:
        try:
            from EasyDialogs import AskPassword 
        except ImportError:
            getpass = default_getpass           
        else:                                   
            getpass = AskPassword
    else:
        getpass = win_getpass
else:
    getpass = unix_getpass

与IDE的日志(甚至是从控制台或终端运行python文件)的区别在于,一旦捕捉到异常,脚本就会立即中断。在

如果您想获取异常并在它发生后做一些事情,例如记录它,那么您需要使用“try except”块。在

我不知道你为什么要避免使用“try except”块,因为它是语言的一个基本特性,就像任何其他决策块(“if”、“while”、“for”等等)一样。在

试着把它看作一个常见的“如果”语句:

if trying this:
    works, great!
else:
    do something with this exception

相关问题 更多 >