有没有办法停止执行exec代码? [重复]

问题描述 投票:-1回答:1

这个问题在这里已有答案:

我有一个程序,通过exec运算符执行代码。

有没有办法停止使用一个运算符执行exec代码,就像我们使用return函数一样?

我尝试使用returnbreak但没有运气。

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代码中有多个端点的情况下。

python exec
1个回答
-1
投票

你可以继承Exception

class StopExec(Exception):
    pass

当你想退出raise StopExec代码块时,在你的代码中使用exec

© www.soinside.com 2019 - 2024. All rights reserved.