我正在编写一个脚本,在其中我需要尝试对电子邮件应用几种解析方法。因此,如果第一个成功,则无需尝试其他的。到目前为止,我只有2种解析方法,但有可能我会添加更多解析方法。如果可能的话,我想复制一个类似switch case的东西(在2.7中不存在)。有比我正在做的更好的事吗?
try:
found['PhishMe_Informations']=self.parse_phishme(message)
except MalformedPhishMeMailError as e:
self.log.error(e[0])
found['PhishMe_Informations']=e[1]
found['PhishMe_Informations']['Malformed']=True
except Exception:
try:
found['Journaling_Informations']=self.parse_journaling(message)
except MalformedRecordMessageError as e:
self.log.error(e)
except Exception:
pass
答案 0 :(得分:0)
您可以尝试在声明模式下构建功能和可能的异常的分层树,然后编写处理该树的代码。在您的用例中,可能是:
{ cls.parse_phishme: OrderedDict(
(MalformedPhishMeMailError, cls.process_malformed),
(Exception, { cls.parse_journaling: OrderedDict(
(MalformedRecordMessageError, cls.log_err),
(Exception, None)
)
)
}
处理该树的方法可能是:
def process_exc_tree(self, d, message):
if isinstance(d, dict): # is d a (possibly ordered) dict?
for func, exc in d.items():
try:
self.func(message) # call the function passed as key
except Exception as e: # process the exceptions
for ex, suite in exc.items(): # passed as ordered dict
if isinstance(e, ex):
# Ok found the relevant exception: recurse
self.process_exc_tree(suite, message)
elif d is None: # if d is None, do nothing
pass
else: # it should be a function: call it
self.d(message)