首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何尝试一些东西,如果失败了,尝试其他的东西?

如何尝试一些东西,如果失败了,尝试其他的东西?
EN

Stack Overflow用户
提问于 2019-02-25 20:56:29
回答 1查看 68关注 0票数 0

我正在写一个脚本,我需要尝试在一封电子邮件上应用几种解析方法。因此,如果第一个成功了,就没有必要尝试其他的了。到目前为止,我只有2个解析方法,但我可能会添加更多。如果可能的话,我想复制一些类似switch case的东西(在2.7中不存在)。有没有比我现在做的更好的?

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2019-02-25 22:51:36

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

代码语言:javascript
复制
{ cls.parse_phishme: OrderedDict(
        (MalformedPhishMeMailError, cls.process_malformed),
        (Exception, { cls.parse_journaling: OrderedDict(
                (MalformedRecordMessageError, cls.log_err),
                (Exception, None)
            )
    )
}

处理该树的方法可以是:

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54866728

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档