1

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

Riven
  • 375
  • 2
  • 11
  • 1
    You can use `exec`, take a look at the code below, I've updated my answer. You can't get the return value from that code. Instead you can print it there itself. – Som Shekhar Mukherjee Apr 03 '21 at 08:55
  • 1
    My example code "requires" a return statement that I can store in `output` though, so its not the solution that I'm looking for. Thanks for the response anyways. – Riven Apr 03 '21 at 09:05

2 Answers2

5

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.

Warlax56
  • 1,170
  • 5
  • 30
1

You can use the exec function. You can't get the return value from the code variable. Instead you can print it there itself.

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

exec(code)
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28