如何在Python 3中的exec命令中停止执行? [英] How do I stop execution inside exec command in Python 3?

查看:175
本文介绍了如何在Python 3中的exec命令中停止执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

code = """
print("foo")

if True: 
    return

print("bar")
"""

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

如果我运行它,我将得到:

If I run it I get:

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调用后解释器可以工作.

How to force exec stop without errors? Probably I should replace return with something? Also I want the interpreter work after exec call.

推荐答案

在这里,只需执行以下操作即可:

Here, just do something like this:

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

如果您担心可读性,功能就是您的第一道防线.

If your worry is readability, functions are your first line of defense.

这篇关于如何在Python 3中的exec命令中停止执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆