Python 2.71中sys.exc_info()[1]的类型和格式
在Windows XP上使用Python 2.71时,我需要用到FTP。
我的代码是:
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
但是在最后一行我遇到了一个错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xea in position 38: ordinal not in range(128)
因为我在法语的Windows环境下,所以sys.exc_info()[1]的内容是:[Errno 10061] Aucune connexion n'a pu être établie car l'ordinateur cible l'a expressément refusée
请问,最有效的方式来格式化sys.exc_info()[1]是什么?
2 个回答
4
value
是一个错误类的实例。你想把它格式化成字符串,但这不太可能。看起来你是想获取与这个错误相关的信息。这个信息可以在 value.message
中找到。试试这个:
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
0
好的,我找到的最好方法是使用 traceback,像这样:
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())