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

2023-12-28

我有以下代码:

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 call.


在这里,只需做这样的事情:

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Python 3 中停止执行 exec 命令? 的相关文章

随机推荐