gpt4 book ai didi

Python 异常控制/流程问题

转载 作者:太空宇宙 更新时间:2023-11-03 13:22:53 25 4
gpt4 key购买 nike

我一直在使用 Python 工作,遇到了一些一定很常见的事情。我有五个陈述都陷入了一个共同的陷阱FooException 和 BarException。我想运行它们中的每一个,防止这些异常但继续处理,即使在之后引发异常一些处理已经完成。现在,我可以这样做:

try:
foo()
except (FooException, BarException):
pass
try:
bar()
except (FooException, BarException):
pass
try:
baz()
except (FooException, BarException):
pass
try:
spam()
except (FooException, BarException):
pass
try:
eggs()
except (FooException, BarException):
pass

但这确实很冗长,而且极度违反 DRY。相当蛮力明显的解决方案是这样的:

def wish_i_had_macros_for_this(statements, exceptions, gd, ld):                
""" execute statements inside try/except handling exceptions with gd and ld
as global dictionary and local dictionary

statements is a list of strings to be executed as statements
exceptions is a list of strings that resolve to Exceptions
gd is a globals() context dictionary
ld is a locals() context dictionary

a list containing None or an Exception if an exception that wasn't
guarded against was raised during execution of the statement for each
statement is returned
"""
s = """
try:
$STATEMENT
except (%s):
pass
""" % ','.join(exceptions)
t = string.Template(s)
code = [t.substitute({'STATEMENT': s}) for s in statements]
elist = list()
for c in code:
try:
exec c in gd, ld
elist.append(None)
except Exception, e:
elist.append(e)
return elist

按照以下方式使用:

>>> results = wish_i_had_macros_for_this(
['foo()','bar()','baz','spam()','eggs()'],
['FooException','BarException'],
globals(),
locals())
[None,None,None,SpamException,None]

有没有更好的办法?

最佳答案

def execute_silently(fn, exceptions = (FooException, BarException)):
try:
fn()
except Exception as e:
if not isinstance(e, exceptions):
raise

execute_silently(foo)
execute_silently(bar)
# ...
# or even:
for fn in (foo, bar, ...):
execute_silently(fn)

关于Python 异常控制/流程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8141527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com