python异常消息捕获

Hel*_*nar 444 python logging exception except

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))
Run Code Online (Sandbox Code Playgroud)

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

eum*_*iro 627

您必须定义要捕获的异常类型.所以写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:
    logger.error('Failed to upload to ftp: '+ str(e))
Run Code Online (Sandbox Code Playgroud)

在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:
    logger.error('Failed to upload to ftp: '+ str(e))
Run Code Online (Sandbox Code Playgroud)

  • repr(e)给你异常(和消息字符串); str(e)只给出消息字符串. (86认同)
  • Python3中的@CharlieParker写了`除了Exception为e:` (24认同)
  • 作为记录异常的替代方法,您可以使用`logger.exception(e)`代替.它将在同一个`logging.ERROR`级别使用traceback记录异常. (9认同)
  • `除了异常,e:`在python 3中向我抛出一个语法错误.这是预期的吗? (6认同)
  • 这在 2020 年有点误导,因为没有人拥有需要您第一种方式的 Python 版本(没有人使用 Python <2.7),但您的答案使这看起来像是 Python 2 中的默认方式,即使第二种方式是几乎总是更好。您应该删除第一种方式,从而使答案更清晰。 (4认同)
  • @mbdevpl 这似乎不是真的。它似乎在异常上调用 str():http://ideone.com/OaCOpO (2认同)

sjt*_*eri 267

python 3中不再支持该语法.请改用以下内容.

try:
    do_something()
except BaseException as e:
    logger.error('Failed to do something: ' + str(e))
Run Code Online (Sandbox Code Playgroud)

  • 请注意`除了BaseException`和`除了Exception`之外不在同一级别.`除了Exception`在Python3中工作,但它不会捕获`KeyboardInterrupt`(如果你想能够中断代码,这可能非常方便!),而`BaseException`捕获任何异常.有关异常的层次结构,请参阅[此链接](https://docs.python.org/3/library/exceptions.html#exception-hierarchy). (7认同)
  • @avyfain - 你错了.语句`logging.error('foo%s',str(e))`将始终将`e`转换为字符串.为了实现你的后续,你将使用`logging.error('foo%s',e)` - 从而允许日志框架执行(或不执行)转换. (6认同)
  • 实际上,你应该使用logger.error('无法做某事:%s',str(e))这样,如果你的记录器级别高于错误,它就不会进行字符串插值. (2认同)
  • 作为记录异常的一种替代方法,您可以使用`logger.exception(e)`。它将以相同的`logging.ERROR`级别记录带有追溯的异常。 (2认同)
  • 我认为他/她的意思是“除了例外,e:” (2认同)

ber*_*iey 38

将此更新为更简单的记录器(适用于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 ...
Run Code Online (Sandbox Code Playgroud)

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

import sys, traceback

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

exc_value是错误消息.

  • 这将是我的首选方法。我想只是打印字符串对于记录日志很有用,但是如果我需要对这些信息做任何事情,我需要的不仅仅是一个字符串。 (3认同)
  • 您不需要在第二个示例中“导入回溯”,对吗? (3认同)

Sli*_*eam 30

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

try:
  ...
except Exception as e:
  print(e.message)
Run Code Online (Sandbox Code Playgroud)

  • 例如,如果你除了e.ece的异常,而`e`是一个'IOError`,你就会得到`e.errno`,`e.filename`和`e.strerror`,但是显然没有'e.message`(至少在Python 2.7.12中).如果要捕获错误消息,请使用`str(e)`,与其他答案一样. (40认同)
  • @HeribertoJuárez 为什么要捕获特殊情况,而您可以简单地将其转换为字符串? (2认同)

Pet*_*ter 18

您可以使用logger.exception("msg")跟踪来记录异常:

try:
    #your code
except Exception as e:
    logger.exception('Failed: ' + str(e))
Run Code Online (Sandbox Code Playgroud)

  • 或者只是`logger.exception(e)`. (5认同)

Kav*_*uwa 15

如果需要错误类,错误消息和堆栈跟踪(或其中一些),请使用sys.exec_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)
Run Code Online (Sandbox Code Playgroud)

给出以下输出:

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

sys.exec_info()

这为您提供有关最新异常的详细信息。返回的元组(type, value, traceback)

traceback是回溯对象的实例。您可以使用提供的方法来格式化跟踪。在追溯文档中可以找到更多内容

  • 使用`e .__ class __.__ name__`也可以返回异常类。 (3认同)

sta*_*iet 13

如果您想查看原始错误消息,(文件行号

import traceback
try:
    print(3/0)
except Exception as e:    
    traceback.print_exc() 
Run Code Online (Sandbox Code Playgroud)

这将显示与您没有使用相同的错误消息try-except


jdh*_*hao 11

使用str(e)repr(e)来表示异常,您将无法获得实际的堆栈跟踪,因此查找异常所在的位置无济于事。

阅读其他答案和日志包文档后,以下两种方法非常适合打印实际堆栈跟踪以便于调试:

logger.debug()与参数一起使用exc_info

try:
    # my code
except SomeError as e:
    logger.debug(e, exc_info=True)
Run Code Online (Sandbox Code Playgroud)

logger.exception()

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

try:
    # my code
except SomeError as e:
    logger.exception(e)
Run Code Online (Sandbox Code Playgroud)


Chu*_* Ma 10

在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}")
Run Code Online (Sandbox Code Playgroud)


小智 7

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

except Attribute as e:
    print(e)
Run Code Online (Sandbox Code Playgroud)


小智 6

在 Python 3 中,str(ex)给我们错误消息。您可以用来repr(ex)获取全文,包括引发的异常的名称。

arr = ["a", "b", "c"]

try:
    print(arr[5])
except IndexError as ex:
    print(repr(ex)) # IndexError: list index out of range
    print(str(ex)) # list index out of range
Run Code Online (Sandbox Code Playgroud)


Ill*_*tor 6

还有一种方法可以获取传递给异常类的原始值,而无需更改内容类型。

例如,我在我的框架之一中提出带有错误消息的类型代码。

try:
    # TODO: Your exceptional code here 
    raise Exception((1, "Your code wants the program to exit"))

except Exception as e:
    print("Exception Type:", e.args[0][0], "Message:", e.args[0][1])
Run Code Online (Sandbox Code Playgroud)

输出

Exception Type: 1 Message: 'Your code wants the program to exit'

Run Code Online (Sandbox Code Playgroud)


Hei*_*son 5

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

try:
  do_something()
except BaseException, e:
  logger.error('Failed to do something: ' + str(e))
Run Code Online (Sandbox Code Playgroud)


Nir*_*edi 5

使用 str(ex) 打印 execption

try:
   #your code
except ex:
   print(str(ex))
Run Code Online (Sandbox Code Playgroud)