sys.exc_info()[1] type and format in Python 2.71

2019-06-13 18:03发布

问题:

In python 2.71 on Windows XP I need to use FTP. My code is :

try:
    ftp = FTP(trec.address)
    ftp.login(trec.login, trec.passw)
    s = ftp.retrlines('LIST ' + trec.filetype)
    ftp.quit()
except:
    (type, value, tb) = sys.exc_info()
    reponse = "%s" % value

But I have an error on the last line : UnicodeDecodeError: 'ascii' codec can't decode byte 0xea in position 38: ordinal not in range(128)
As I am in French Windows env. the sys.exc_info()[1] is : [Errno 10061] Aucune connexion n'a pu être établie car l'ordinateur cible l'a expressément refusée
What is the most efficient way to format sys.exc_info()[1] ?

回答1:

value is an instance of the Error class. You want to format it as a string. This is impossible. It seems you want to get the message associated with the error. That message can be found in value.message. Try this:

try:
    ftp = FTP(trec.address)
    ftp.login(trec.login, trec.passw)
    s = ftp.retrlines('LIST ' + trec.filetype)
    ftp.quit()
except:
    type, value, tb = sys.exc_info()
    reponse = "%s" % value.message


回答2:

OK, the best way I found is to use traceback like this :

import traceback

def trace_except(sysexecinfo, smessage = ''):
   """ Trace exceptions """
   exc_type, exc_value, exc_traceback = sysexecinfo
   i, j = (traceback.extract_tb(exc_traceback, 1))[0][0:2]
   k = (traceback.format_exception_only(exc_type, exc_value))[0]
   trace('E:'+ 'Err : ' + smessage + k + i + ', ligne ' + str(j))
   return k

 try:
   ftp = FTP(trec.address)
   ftp.login(trec.login, trec.passw)
   s = ftp.retrlines('LIST ' + trec.filetype)
   ftp.quit() 
 except:
    reponse = trace_except(sys.exc_info())