Search code examples
pythonpippythoninterpreter

Interpret python code within python program


Is there a library for interpreting python code within a python program?
Sample usage might look like this..

code = """
def hello():
    return 'hello'

hello()
"""

output = Interpreter.run(code)
print(output)

which then outputs hello


Solution

  • found this example from grepper

    the_code = '''
    a = 1
    b = 2
    return_me = a + b
    '''
    
    loc = {}
    exec(the_code, globals(), loc)
    return_workaround = loc['return_me']
    print(return_workaround)
    

    apparently you can pass global and local scope into exec. In your use case, you would just use a named variable instead of returning.