您想要的是某些语言中存在的选项,异常处理程序可以选择继续处理下一个异常。这曾经导致代码不佳,AFAIK 从未在 Python 中实现。背后的基本原理是,您必须明确说明您希望如何处理异常以及您希望在哪里继续处理。
在您的情况下,假设您有一个名为 main 的函数,它只调用其他函数并自动生成,我的建议是在生成和执行之间对其进行后期处理。检查模块甚至可以允许在运行时执行此操作:
def filter_exc(func):
src = inspect.getsource(func)
lines = src.split('\n')
out = lines[0] + "\n"
for line in lines[1:]:
m = re.match('(\s*)(.*)', line)
lead, text = m.groups()
# ignore comments and empty lines
if not (text.startswith('#') or text.strip() == ""):
out += lead + "try:\n"
out += lead + " " + text + "\n"
out += lead + "except:\n" + lead + " pass\n"
return out
然后您可以使用邪恶的exec(仅来自 your 函数的源中的输入):
exec(filter_exc(main)) # replaces main with the filtered version
main() # will ignore exceptions
在您发表评论后,您想要一个更强大的解决方案,可以处理多行语句和 cmets。在这种情况下,您需要真正解析源代码并修改解析后的树。 ast 救援模块:
class ExceptFilter(ast.NodeTransformer):
def visit_Expr(self, node):
self.generic_visit(node)
if isinstance(node.value, ast.Call): # filter all function calls
# print(node.value.func.id)
# use a dummy try block
n = ast.parse("""try:
f()
except:
pass""").body[0]
n.body[0] = node # make the try call the real function
return n # and use it
return node # keep other nodes unchanged
使用该示例代码:
def func1():
print('foo')
def func2():
raise Exception("Test")
def func3(x):
print("f3", x)
def main():
func1()
# this is a comment
a = 1
if a == 1: # this is a multi line statement
func2()
func3("bar")
我们得到:
>>> node = ast.parse(inspect.getsource(main))
>>> exec(compile(ExceptFilter().visit(node), "", mode="exec"))
>>> main()
foo
f3 bar
在这种情况下,未解析的节点(*)写为:
def main():
try:
func1()
except:
pass
a = 1
if (a == 1):
try:
func2()
except:
pass
try:
func3('bar')
except:
pass
或者,也可以包装每个顶级表达式:
>>> node = ast.parse(inspect.getsource(main))
>>> for i in range(len(node.body[0].body)): # process top level expressions
n = ast.parse("""try:
f()
except:
pass""").body[0]
n.body[0] = node.body[0].body[i]
node.body[0].body[i] = n
>>> exec(compile(node, "", mode="exec"))
>>> main()
foo
f3 bar
这里未解析的树写道:
def main():
try:
func1()
except:
pass
try:
a = 1
except:
pass
try:
if (a == 1):
func2()
except:
pass
try:
func3('bar')
except:
pass
注意:如果您在函数中使用exec(compile(...,则会出现一个有趣的极端情况。默认情况下,exec(code) 是 exec(code, globals(), locals())。在顶层,本地和全局字典是同一个字典,所以顶层函数被正确替换。但是如果你在一个函数中做同样的事情,你只会创建一个同名的本地函数,它只能从函数中调用(当函数返回时它将超出范围)locals()['main']()。因此,您必须通过显式传递全局字典来更改全局函数:
exec(compile(ExceptFilter().visit(node), "", mode="exec"), globals(), globals())
或者返回修改后的函数而不改变原来的函数:
def myfun():
# print(main)
node = ast.parse(inspect.getsource(main))
exec(compile(ExceptFilter().visit(node), "", mode="exec"))
# print(main, locals()['main'], globals()['main'])
return locals()['main']
>>> m2 = myfun()
>>> m2()
foo
f3 bar
(*) Python 3.6 在 Tools/parser 中包含一个 unparser,但在 pypi 中存在一个更简单易用的版本