我正在写一个脚本,我需要尝试在一封电子邮件上应用几种解析方法。因此,如果第一个成功了,就没有必要尝试其他的了。到目前为止,我只有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发布于 2019-02-25 22:51:36
您可以尝试以声明模式构建函数和可能的异常的分层树,然后编写处理它的代码。在您的用例中,它可能是:
{ 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)https://stackoverflow.com/questions/54866728
复制相似问题