python异常消息捕获
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4690600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python exception message capturing
提问by Hellnar
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))
This doesn't seem to work, I get syntax error, what is the proper way of doing this for logging all kind of exceptions to a file
这似乎不起作用,我收到语法错误,将所有类型的异常记录到文件的正确方法是什么
采纳答案by eumiro
You have to define which type of exception you want to catch. So write except Exception, e:instead of except, e:for a general exception (that will be logged anyway).
您必须定义要捕获的异常类型。所以写except Exception, e:而不是except, e:一般的异常(无论如何都会被记录)。
Other possibility is to write your whole try/except code this way:
另一种可能性是以这种方式编写整个 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))
in Python 3.x and modern versions of Python 2.x use except Exception as einstead of except Exception, 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))
回答by Heini H?gnason
You can try specifying the BaseException type explicitly. However, this will only catch derivatives of BaseException. While this includes all implementation-provided exceptions, it is also possibly to raise arbitrary old-style classes.
您可以尝试显式指定 BaseException 类型。但是,这只会捕获 BaseException 的衍生物。虽然这包括所有实现提供的异常,但也可能引发任意的旧式类。
try:
do_something()
except BaseException, e:
logger.error('Failed to do something: ' + str(e))
回答by sjtaheri
The syntax is no longer supported in python 3. Use the following instead.
python 3 不再支持该语法。请改用以下内容。
try:
do_something()
except BaseException as e:
logger.error('Failed to do something: ' + str(e))
回答by berniey
Updating this to something simpler for logger (works for both python 2 and 3). You do not need traceback module.
将此更新为更简单的记录器(适用于 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 ...
This is now the old way (though still works):
这是现在的旧方法(尽管仍然有效):
import sys, traceback
def catchEverything():
try:
... some operation(s) ...
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
... exception handling ...
exc_value is the error message.
exc_value 是错误信息。
回答by Peter
You can use logger.exception("msg")for logging exception with traceback:
您可以使用logger.exception("msg")回溯记录异常:
try:
#your code
except Exception as e:
logger.exception('Failed: ' + str(e))
回答by Slipstream
There are some cases where you can use the e.messageor e.messages.. But it does not work in all cases. Anyway the more safe is to use the str(e)
在某些情况下,您可以使用e.message或e.messages.. 但它并不适用于所有情况。无论如何更安全的是使用str(e)
try:
...
except Exception as e:
print(e.message)
回答by Kavindu Dodanduwa
If you want the error class, error message and stack trace (or some of those), use sys.exec_info().
如果您想要错误类、错误消息和堆栈跟踪(或其中一些),请使用sys.exec_info().
Minimal working code with some formatting:
具有某种格式的最小工作代码:
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)
Which gives the following output:
这给出了以下输出:
Exception type : ZeroDivisionError
Exception message : division by zero
Stack trace : ['File : .\test.py , Line : 5, Func.Name : <module>, Message : ans = 1/0']
The function sys.exc_info()gives you details about the most recent exception. It returns a tuple of (type, value, traceback).
函数sys.exc_info()为您提供有关最近异常的详细信息。它返回一个元组(type, value, traceback)。
tracebackis an instance of traceback object. You can format the trace with the methods provided. More can be found in the traceback documentation.
traceback是回溯对象的一个实例。您可以使用提供的方法格式化跟踪。更多信息可以在回溯文档中找到。
回答by Niraj Trivedi
Use str(ex) to print execption
使用 str(ex) 打印 execption
try:
#your code
except ex:
print(str(ex))
回答by Chuan Ma
After python 3.6, you can use formatted string literal. It's neat! (https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498)
在 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}")
回答by syter
for the future strugglers, in python 3.8.2(and maybe a few versions before that), the syntax is
对于未来的奋斗者,在 python 3.8.2(可能还有之前的几个版本)中,语法是
except Attribute as e:
print(e)

