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 Exception as 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 as e: # works on python 3.x
logger.error('Failed to upload to ftp: %s', repr(e))
在旧版本的 Python 2.x 中,使用
except Exception, e
而不是 except Exception as e
:
try:
with open(filepath,'rb') as f:
con.storbinary('STOR '+ filepath, f)
logger.info('File successfully uploaded to %s', FTPADDR)
except Exception, e: # works on python 2.x
logger.error('Failed to upload to ftp: %s', repr(e))
python 3 不再支持该语法。请改用以下语法。
try:
do_something()
except BaseException as e:
logger.error('Failed to do something: ' + str(e))
如果您想要错误类、错误消息和堆栈跟踪,请使用
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 文档 中找到。
在某些情况下,您可以使用 e.message 或 e.messages.. 但它并非在所有情况下都有效。无论如何,更安全的是使用 str(e)
try:
...
except Exception as e:
print(e.message)
将其更新为更简单的记录器(适用于 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 是错误消息。
您可以使用
logger.exception("msg")
来记录带有回溯的异常:
try:
#your code
except Exception as e:
logger.exception('Failed: ' + str(e))
使用
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)
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}")
您可以尝试显式指定 BaseException 类型。但是,这只会捕获 BaseException 的派生类。虽然这包括所有实现提供的异常,但也可能引发任意旧式类。
try:
do_something()
except BaseException, e:
logger.error('Failed to do something: ' + str(e))
如果您想查看原始错误消息,(文件&行号)
import traceback
try:
print(3/0)
except Exception as e:
traceback.print_exc()
这将向您显示与未使用
try-except
相同的错误消息。
对于未来的奋斗者, 在 python 3.8.2(可能还有之前的几个版本)中,语法是
except Attribute as e:
print(e)
在 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
还有一种方法可以将原始值传递给异常类,而无需更改内容类型。
例如,我在我的框架之一中提出带有错误消息的类型代码。
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])
输出
Exception Type: 1 Message: 'Your code wants the program to exit'
使用str(ex)打印执行
try:
#your code
except ex:
print(str(ex))
最简单的方法是通过 Polog 库实现这一点。导入它:
$ pip install polog
并使用:
from polog import log, config, file_writer
config.add_handlers(file_writer('file.log'))
with log('message').suppress():
do_something()
注意代码垂直占用的空间少了多少:只有 2 行。