python istisna mesajı yakalama

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

Bu işe yaramıyor gibi görünüyor, sözdizimi hatası alıyorum, her türlü istisnayı bir dosyaya kaydetmek için bunu yapmanın doğru yolu nedir

Çözüm

Hangi tür istisnayı yakalamak istediğinizi tanımlamanız gerekir. Bu nedenle, genel bir istisna için (zaten günlüğe kaydedilecek) except, e: yerine except Exception, e: yazın.

Diğer bir olasılık ise tüm try/except kodunuzu bu şekilde yazmaktır:

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 ve Python 2.x'in modern sürümlerinde except Exception, e yerine except Exception as e kullanılır:

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))
Yorumlar (6)

Bu sözdizimi artık python 3'te desteklenmemektedir. Bunun yerine aşağıdakileri kullanın.

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

BaseException türünü açıkça belirtmeyi deneyebilirsiniz. Ancak, bu yalnızca BaseException türevlerini yakalayacaktır. Bu, uygulama tarafından sağlanan tüm istisnaları içerirken, rastgele eski tarz sınıfları yükseltmek de mümkündür.

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