在python3中,如何停止exec命令内的执行?

2024-04-18 18:57:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

code = """
print("foo")

if True: 
    return

print("bar")
"""

exec(code)
print('This should still be executed')

如果我运行它,我得到:

^{pr2}$

如何强制exec停止而不出错?也许我应该用某物取代return?我还想让解释器在exec调用后工作。在


Tags: 代码truereturniffoobarcodebe
3条回答

这将起作用,return只在定义的函数中起作用:

code = """
print("foo")

if not True:
    print("bar")
"""
exec(code)
print('This should still be executed')

但如果要使用return,则必须执行以下操作:

^{pr2}$

在这里,做这样的事情:

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')

如果您担心的是可读性,那么函数就是您的第一道防线。在

没有允许您中止exec调用执行的内置机制。最接近的是^{},但它退出了整个程序,而不仅仅是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

相关问题 更多 >