Python异常信息捕获

910
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))

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


3
你的缩进有问题。并且在except后面省略逗号。 - Sven Marnach
4
如果你在except之后省略逗号,你会得到global name 'e' is not defined的错误提示,这并没有比语法错误好多少。请注意不要改变原意。 - Val
20
@Val: 根据Python的版本,应该是 except Exception as eexcept Exception, e - Sven Marnach
1
可能在这8个答案中的某个地方,但是当你打开一个文件时,关闭部分不应该在try语句中,而应该在finally语句中或者被with语句包装。 - user4396006
你可以像requests包中的UnitTests一样做 https://fixexception.com/requests/expected-exception/ - Ivan Borshchov
15个回答

7

对于未来的初学者,在Python 3.8.2(以及可能是之前的几个版本)中,语法为:

except Attribute as e:
    print(e)

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

5

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

例如,我在我的一个框架中使用错误消息引发类型代码。

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'


4
使用 str(ex) 打印异常。
try:
   #your code
except ex:
   print(str(ex))

0

最简单的方法是通过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行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接