如何尝试某样东西,如果失败了,就尝试别的东西?

2024-10-01 07:33:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个脚本,我需要尝试在一封电子邮件上应用几种解析方法。因此,如果第一个成功了,就没有必要尝试其他的。到目前为止,我只有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

Tags: 方法self脚本logmessageparseasexception
1条回答
网友
1楼 · 发布于 2024-10-01 07:33:45

您可以尝试在声明模式中构建函数和可能异常的层次结构树,然后编写处理它的代码。在您的用例中,它可以是:

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

相关问题 更多 >