On Error在Python中继续下一步

栏目: Python · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/26059424/on-error-resume-next-in-python

片段1

do_magic() # Throws exception, doesn't execute do_foo and do_bar
do_foo()
do_bar()

片段2

try:
    do_magic() # Doesn't throw exception, doesn't execute do_foo and do_bar
    do_foo() 
    do_bar()
except:
    pass

片段3

try: do_magic(); except: pass
try: do_foo()  ; except: pass
try: do_bar()  ; except: pass

有没有办法优雅地编写代码片段3?

>如果do_magic()失败或不执行,则应执行do_foo()和do_bar().

>如果do_foo()失败或不执行,则应执行do_bar().

在Basic / Visual Basic / VBS中,有一个名为On Error Resume Next的语句执行此操作.

Python 3.4及更高版本中,您可以使用 contextlib.suppress
from contextlib import suppress

with suppress(Exception): # or, better, a more specific error (or errors)
    do_magic()
with suppress(Exception):
    do_foo()
with suppress(Exception):
    do_bar()

或者, fuckit .

翻译自:https://stackoverflow.com/questions/26059424/on-error-resume-next-in-python


以上所述就是小编给大家介绍的《On Error在Python中继续下一步》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

软件测试的艺术

软件测试的艺术

梅尔斯 / 机械工业出版社 / 2006年01月 / 22.0

《软件测试的艺术》(原书第2版)成功、有效地进行软件测试的实用策略和技术:    基本的测试原理和策略      验收测试    程序检查和走查         安装测试    代码检查            模块(单元)测试    错误列表            测试规划与控制    同行评分            独立测试机构    黑盒、白盒测试    ......一起来看看 《软件测试的艺术》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试