这个问题在这里已有答案:
我有一个程序,通过exec
运算符执行代码。
有没有办法停止使用一个运算符执行exec代码,就像我们使用return
函数一样?
我尝试使用return
和break
但没有运气。
condition = True
my_code = """
print ("foo")
if condition:
return # this is not working
print ("bar")
"""
exec(my_code)
可能的解决方案是将条件块1缩进更深。
my_code = """
print ("foo")
if not condition:
print ("bar")
"""
但是,这看起来并不整齐。特别是在exec代码中有多个端点的情况下。
你可以继承Exception
:
class StopExec(Exception):
pass
当你想退出raise StopExec
代码块时,在你的代码中使用exec
。