Python is an interpreted language, and the interpreter features are exposed in the standard library too.
This means that we can evaluate expressions and statements coming from files or text sources and have them run as Python code within Python code itself.
It's also possible to evaluate code in a fairly safe way that allows us to create objects from expressions but prevents the execution of any function.
The steps for this recipe are as follows:
- The
eval
,exec
, andast
functions and modules provide most of the machinery needed for execution of code from strings:
import ast def run_python(code, mode='evalsafe'): if mode == 'evalsafe': return ast.literal_eval(code) elif mode == 'eval': return eval(compile(code, '', mode='eval')) elif mode == 'exec': return exec(compile(code, '', mode='exec')) else: raise ValueError('Unsupported execution model {}'.format(mode))
- The
run_python
function inevalsafe...