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, e: 代替 except, e: 对于一般例外(无论如何将记录)。

其他可能性是以这种方式编写整个尝试/除了代码以外:

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

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

其他提示

语法在Python 3中不再支持3.使用以下内容。

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

将其更新为更简单的记录器(适用于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是错误消息。

在某些情况下,您可以使用 E.Message 或者 E.Messages..但是,在所有情况下都不起作用。无论如何,更安全的就是使用 str(e)

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

您可以使用 logger.exception("msg") 对于登录例,Trackback的例外:

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

如果您想要错误类,错误消息和堆栈跟踪(或其中的任何一个),请使用 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)

这将发出以下输出,

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

sys.exec_info()

这为您提供了有关最新异常的例外详细信息。它返回元组。以下是元组值 (type, value, traceback).

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

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类型。但是,这只会捕获基本感受的衍生物。虽然这包括所有实现的例外,但也可能提高任意的老式类别。

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

使用str(ex)打印执行

try:
   #your code
except ex:
   print(str(ex))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top