I have a following code:
code = """
print("foo")
if True:
return
print("bar")
"""
exec(code)
print('This should still be executed')
If I run it I get:
Traceback (most recent call last):
File "untitled.py", line 10, in
exec(code)
File "", line 5
SyntaxError: 'return' outside function
How to force exec stop without errors? Probably I should replace return with something? Also I want the interpreter work after exec call.
解决方案
Here, just do something like this:
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')
If your worry is readability, functions are your first line of defense.