Riven
Riven

Reputation: 375

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

Upvotes: 1

Views: 204

Answers (2)

Warlax56
Warlax56

Reputation: 1212

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.

Upvotes: 5

Som Shekhar Mukherjee
Som Shekhar Mukherjee

Reputation: 8168

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)

Upvotes: 1

Related Questions