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.
To stop a python script, just press Ctrl + C. Use the exit() function to terminate Python script execution programmatically.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With