Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

exec

I have a following code:

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

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

like image 433
Fomalhaut Avatar asked Aug 18 '18 04:08

Fomalhaut


People also ask

How do I stop Python exec?

To stop a python script, just press Ctrl + C. Use the exit() function to terminate Python script execution programmatically.

What is quit () in Python?

The quit() Function Python's in-built quit() function exits a Python program by closing the Python file. Since the quit() function requires us to load the site module, it is generally not used in production code.

How do you force exit a function in Python?

Technique 1: Using quit() function The in-built quit() function offered by the Python functions, can be used to exit a Python program. As soon as the system encounters the quit() function, it terminates the execution of the program completely.

How do you pause a code in Python?

Python sleep() function will pause Python code or delay the execution of program for the number of seconds given as input to sleep(). The sleep() function is part of the Python time module. You can make use of Python sleep function when you want to temporarily halt the execution of your code.


1 Answers

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.

like image 124
juanpa.arrivillaga Avatar answered Oct 03 '22 08:10

juanpa.arrivillaga