如何在 Python 3 的 exec 命令中停止执行?

How do I stop execution inside exec command in Python 3?

我有以下代码:

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 通话后工作。

这会起作用,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')

在这里,做这样的事情:

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 调用的内置机制。我们拥有的最接近的东西是 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 executed

只是为了好玩,这是另一种方式:

def breakable_exec(code):
    exec('for _ in [0]:' + '\n'.join("    " + line for line in code.splitlines()))

code = """
print("foo")

if True: 
    break

print("bar")
"""

breakable_exec(code)
# => foo