how to exit exec() like in a function in Python
Question:
I’m currently trying to make an self-modifying algorithm in Python.
To do that, i have a string containing an algorithm that i run using the exec(algorithm) function inside another funciton.
the algorithm that i want to run looks like this :
if (a):
do_something()
return
if (b):
do_something_else()
return
...
the problem is that "exec()" does not act like a function and so the "return" won’t work as such.
Of course, it works when i modify the algorithm string into :
def function ():
if (a):
do_something()
return
if (b):
do_something_else()
return
...
function()
But what i want is the keyword that replace "return" in exec().
The keyword that only exits the exec() (not the whole program), if it exists
Answers:
You can use the sys.exit() function to exit from within the exec() function without terminating the entire program. You just need to catch the SystemExit exception that sys.exit() raises and handle it appropriately.
import sys
def run_algorithm(algorithm):
try:
exec(algorithm)
except SystemExit:
pass
algorithm = ”’
if a:
print("a is true")
sys.exit()
if b:
print("b is true")
sys.exit()
”’
run_algorithm(algorithm)
I’m currently trying to make an self-modifying algorithm in Python.
To do that, i have a string containing an algorithm that i run using the exec(algorithm) function inside another funciton.
the algorithm that i want to run looks like this :
if (a):
do_something()
return
if (b):
do_something_else()
return
...
the problem is that "exec()" does not act like a function and so the "return" won’t work as such.
Of course, it works when i modify the algorithm string into :
def function ():
if (a):
do_something()
return
if (b):
do_something_else()
return
...
function()
But what i want is the keyword that replace "return" in exec().
The keyword that only exits the exec() (not the whole program), if it exists
You can use the sys.exit() function to exit from within the exec() function without terminating the entire program. You just need to catch the SystemExit exception that sys.exit() raises and handle it appropriately.
import sys
def run_algorithm(algorithm):
try:
exec(algorithm)
except SystemExit:
pass
algorithm = ”’
if a:
print("a is true")
sys.exit()
if b:
print("b is true")
sys.exit()
”’
run_algorithm(algorithm)