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

2024/9/30 20:37:45

I have a following code:

code = """
print("foo")if True: returnprint("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

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

Answer

Here, just do something like this:

class ExecInterrupt(Exception):passdef Exec(source, globals=None, locals=None):try:exec(source, globals, locals)except ExecInterrupt:passExec("""
print("foo")if True: raise ExecInterruptprint("bar")
""")
print('This should still be executed')

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

https://en.xdnf.cn/q/70946.html

Related Q&A

sqlalchemy concurrency update issue

I have a table, jobs, with fields id, rank, and datetime started in a MySQL InnoDB database. Each time a process gets a job, it "checks out" that job be marking it started, so that no other p…

Python matplotlib: Change axis labels/legend from bold to regular weight

Im trying to make some publication-quality plots, but I have encountered a small problem. It seems by default that matplotlib axis labels and legend entries are weighted heavier than the axis tick mark…

Negative extra_requires in Python setup.py

Id like to make a Python package that installs a dependency by default unless the user specially signals they do not want that.Example:pip install package[no-django]Does current pip and setup.py mechan…

Get Type in Robot Framework

Could you tell me about how to get the variable type in Robot Framework.${ABC} Set Variable Test ${XYZ} Set Variable 1233Remark: Get the variable Type such as string, intget ${ABC} type = strin…

Keras 2, TypeError: cant pickle _thread.lock objects

I am using Keras to create an ANN and do a grid search on the network. I have encountered the following error while running the code below:model = KerasClassifier(build_fn=create_model(input_dim), verb…

How to remove minimize/maximize buttons while preserving the icon?

Is it possible to display the icon for my toplevel and root window after removing the minimize and maximize buttons? I tried using -toolwindow but the icon cant be displayed afterwards. Is there anoth…

Undefined reference to `PyString_FromString

I have this C code:... [SNIP] ... for(Node = Plugin.Head; Node != NULL; Node = Node->Next) {//Create new python sub-interpreterNode->Interpreter = Py_NewInterpreter();if(Node->Interpreter == N…

How to call a method from a different blueprint in Flask?

I have an application with multiple blueprinted modules.I would like to call a method (a route) that would normally return a view or render a template, from within a different blueprints route.How can …

Dynamically define functions with varying signature

What I want to accomplish:dct = {foo:0, bar:1, baz:2} def func(**dct):pass #function signature is now func(foo=0, bar=1, baz=2)However, the ** syntax is obviously clashing here between expanding a dict…

python pandas plot with uneven timeseries index (with count evenly distributed)

My dataframe has uneven time index.how could I find a way to plot the data, and local the index automatically? I searched here, and I know I can plot something like e.plot()but the time index (x axis)…