我有以下代码:
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调用后解释器工作。
发布于 2018-08-18 12:35:12
在这里,只需这样做:
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')如果你担心的是可读性,那么函数是你的第一道防线。
发布于 2018-08-18 12:21:31
这将起作用,return仅在已定义的函数中起作用:
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')发布于 2019-03-28 17:24:11
没有内置的机制允许您中止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 executedhttps://stackoverflow.com/questions/51905191
复制相似问题