Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to exit exec() like in a function in Python

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   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

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading