我有以下代码:
code = """
print("foo")
if True:
return
print("bar")
"""
exec(code)
print('This should still be executed')
如果我运行它,我将得到:
Traceback (most recent call last):
File "untitled.py", line 10, in <module>
exec(code)
File "<string>", line 5
SyntaxError: 'return' outside function
如何强制exec
无错误停止?可能我应该将return
替换为某些内容?我也希望在exec
通话后翻译工作。
答案 0 :(得分:2)
在这里,做这样的事情:
class ExecInterrupt(Exception):
pass
def Exec(source, globals=None, locals=None):
try:
exec(source, globals, locals)
except ExecInterrupt:
pass
Exec("""
print("foo")
if True:
raise ExecInterrupt
print("bar")
""")
print('This should still be executed')
如果您担心可读性,那么功能就是第一道防线。
答案 1 :(得分:1)
这将起作用,仅在定义的函数内返回才有效:
code = """
print("foo")
if not True:
print("bar")
"""
exec(code)
print('This should still be executed')
但如果要使用return,则必须执行以下操作:
code = """
def func():
print("foo")
if True:
return
print("bar")
func()
"""
exec(code)
print('This should still be executed')
答案 2 :(得分:1)
没有内置机制可让您中止exec
调用的执行。我们拥有的最接近的东西是sys.exit()
,但这退出了整个程序,而不仅仅是exec
。幸运的是,这可以通过少量的异常处理样板来解决:
my_code = """
import sys
print("foo")
if True:
sys.exit()
print("bar")
"""
try:
exec(my_code)
except SystemExit:
pass
print('This is still executed')
# output:
# foo
# This is still executed
答案 3 :(得分:1)
只是为了好玩,这是另一种方式:
def breakable_exec(code):
exec('for _ in [0]:' + '\n'.join(" " + line for line in code.splitlines()))
code = """
print("foo")
if True:
break
print("bar")
"""
breakable_exec(code)
# => foo