【问题标题】:python exception message capturingpython异常消息捕获
【发布时间】:2011-06-09 02:27:48
【问题描述】:
import ftplib
import urllib2
import os
import logging
logger = logging.getLogger('ftpuploader')
hdlr = logging.FileHandler('ftplog.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
FTPADDR = "some ftp address"

def upload_to_ftp(con, filepath):
    try:
        f = open(filepath,'rb')                # file to send
        con.storbinary('STOR '+ filepath, f)         # Send the file
        f.close()                                # Close file and FTP
        logger.info('File successfully uploaded to '+ FTPADDR)
    except, e:
        logger.error('Failed to upload to ftp: '+ str(e))

这似乎不起作用,我收到语法错误,将所有类型的异常记录到文件中的正确方法是什么

【问题讨论】:

  • 你的缩进被破坏了。并在except 之后省略,
  • @SvenMarnach,如果你在except 后面省略,,你会得到global name 'e' is not defined,这并不比语法错误好多少。
  • @Val: 应该是 except Exception as eexcept Exception, e,取决于 Python 版本。
  • 可能在这 8 个答案附近,但是当你打开一个文件时,关闭部分不应该在 try 语句中,而是在 finally 语句中或被 with 语句包裹。
  • 你可以像请求包中的 UnitTests 那样做 fixexception.com/requests/expected-exception

标签: python exception logging except


【解决方案1】:

您必须定义要捕获的异常类型。所以写except Exception, e:而不是except, e:作为一般异常(无论如何都会被记录)。

另一种可能性是用这种方式编写整个 try/except 代码:

try:
    with open(filepath,'rb') as f:
        con.storbinary('STOR '+ filepath, f)
    logger.info('File successfully uploaded to '+ FTPADDR)
except Exception, e: # work on python 2.x
    logger.error('Failed to upload to ftp: '+ str(e))

在 Python 3.x 和现代版本的 Python 2.x 中使用 except Exception as e 而不是 except Exception, e

try:
    with open(filepath,'rb') as f:
        con.storbinary('STOR '+ filepath, f)
    logger.info('File successfully uploaded to '+ FTPADDR)
except Exception as e: # work on python 3.x
    logger.error('Failed to upload to ftp: '+ str(e))

【讨论】:

  • repr(e) 为您提供异常(和消息字符串); str(e) 只给出消息字符串。
  • 作为记录异常的替代方法,您可以改用logger.exception(e)。它将在相同的logging.ERROR 级别记录带有回溯的异常。
  • @mbdevpl 这似乎不是真的。它似乎在异常上调用 str():ideone.com/OaCOpO
  • except Exception, e: 在 python 3 中向我抛出语法错误。这是预期的吗?
  • @CharlieParker 在 Python3 中写 except Exception as e:
【解决方案2】:

python 3 不再支持该语法。请改用以下语法。

try:
    do_something()
except BaseException as e:
    logger.error('Failed to do something: ' + str(e))

【讨论】:

  • 实际上,你应该使用 logger.error('Failed to do something: %s', str(e)) 这样,如果你的记录器级别高于错误,它就不会进行字符串插值.
  • @avyfain - 你不正确。语句logging.error('foo %s', str(e)) 将始终将e 转换为字符串。为了实现您所追求的,您将使用logging.error('foo %s', e) - 从而允许日志框架执行(或不执行)转换。
  • 作为记录异常的替代方法,您可以改用logger.exception(e)。它将在相同的logging.ERROR 级别记录带有回溯的异常。
  • 我认为他/她的意思是“除了 Exception, e:”
  • 请注意except BaseExceptionexcept Exception 不在同一级别。 except Exception 确实在 Python3 中工作,但它不会捕获 KeyboardInterrupt 例如(如果您希望能够中断代码,这将非常方便!),而 BaseException 捕获任何异常。有关异常的层次结构,请参见 this link
【解决方案3】:

如果您需要错误类、错误消息和堆栈跟踪,请使用 sys.exc_info()

带有一些格式的最小工作代码:

import sys
import traceback

try:
    ans = 1/0
except BaseException as ex:
    # Get current system exception
    ex_type, ex_value, ex_traceback = sys.exc_info()

    # Extract unformatter stack traces as tuples
    trace_back = traceback.extract_tb(ex_traceback)

    # Format stacktrace
    stack_trace = list()

    for trace in trace_back:
        stack_trace.append("File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]))

    print("Exception type : %s " % ex_type.__name__)
    print("Exception message : %s" %ex_value)
    print("Stack trace : %s" %stack_trace)

它给出以下输出:

Exception type : ZeroDivisionError
Exception message : division by zero
Stack trace : ['File : .\\test.py , Line : 5, Func.Name : <module>, Message : ans = 1/0']

sys.exc_info() 函数为您提供有关最近异常的详细信息。它返回一个 (type, value, traceback) 的元组。

traceback 是回溯对象的一个​​实例。您可以使用提供的方法格式化跟踪。更多可以在traceback documentation 中找到。

【讨论】:

  • 使用e.__class__.__name__ 也可以返回异常类。
【解决方案4】:

在某些情况下,您可以使用 e.messagee.messages。但并非在所有情况下都有效。无论如何,更安全的是使用 str(e)

try:
  ...
except Exception as e:
  print(e.message)

【讨论】:

  • 这个问题是,例如,如果你 except Exception as eeIOError,你会得到 e.errnoe.filenamee.strerror,但显然没有e.message(至少在 Python 2.7.12 中)。如果要捕获错误消息,请使用str(e),如其他答案中所示。
  • @epalm 如果在异常之前捕获 IOError 怎么办?
  • @HeribertoJuárez 为什么要捕获特殊情况,而您可以简单地将其转换为字符串?
【解决方案5】:

将此更新为更简单的记录器(适用于 python 2 和 3)。您不需要回溯模块。

import logging

logger = logging.Logger('catch_all')

def catchEverythingInLog():
    try:
        ... do something ...
    except Exception as e:
        logger.error(e, exc_info=True)
        ... exception handling ...

这是现在的旧方法(尽管仍然有效):

import sys, traceback

def catchEverything():
    try:
        ... some operation(s) ...
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        ... exception handling ...

exc_value 是错误信息。

【讨论】:

  • 这将是我的首选方法。我想,仅打印字符串对于记录日志很有用,但如果我需要对这些信息做任何事情,我需要的不仅仅是一个字符串。
  • 第二个例子你不需要'import traceback',对吧?
【解决方案6】:

您可以使用logger.exception("msg") 记录带有回溯的异常:

try:
    #your code
except Exception as e:
    logger.exception('Failed: ' + str(e))

【讨论】:

  • 巧合的是,e.msgException 类的字符串表示形式。
  • 或者干脆logger.exception(e)
【解决方案7】:

在 python 3.6 之后,您可以使用格式化字符串文字。很整洁! (https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498)

try
 ...
except Exception as e:
    logger.error(f"Failed to upload to ftp: {e}")

【讨论】:

    【解决方案8】:

    使用str(e)repr(e) 表示异常,您将无法获得实际的堆栈跟踪,因此查找异常在哪里没有帮助。

    在阅读了其他答案和日志包文档之后,以下两种方法可以很好地打印实际的堆栈跟踪,以便于调试:

    使用logger.debug() 和参数exc_info

    try:
        # my code
    except SomeError as e:
        logger.debug(e, exc_info=True)
    

    使用logger.exception()

    或者我们可以直接使用logger.exception()打印异常。

    try:
        # my code
    except SomeError as e:
        logger.exception(e)
    

    【讨论】:

      【解决方案9】:

      您可以尝试明确指定 BaseException 类型。但是,这只会捕获 BaseException 的衍生物。虽然这包括所有实现提供的异常,但也可能引发任意旧式类。

      try:
        do_something()
      except BaseException, e:
        logger.error('Failed to do something: ' + str(e))
      

      【讨论】:

        【解决方案10】:

        使用 str(ex) 打印执行

        try:
           #your code
        except ex:
           print(str(ex))
        

        【讨论】:

          【解决方案11】:

          为了未来的奋斗者, 在python 3.8.2(可能还有之前的几个版本)中,语法是

          except Attribute as e:
              print(e)
          

          【讨论】:

            【解决方案12】:

            如果你想查看原始错误信息,(file & line number)

            import traceback
            try:
                print(3/0)
            except Exception as e:    
                traceback.print_exc() 
            

            这将向您显示与未使用 try-except 相同的错误消息。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2010-11-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-02-01
              相关资源
              最近更新 更多