Skip to content

Instantly share code, notes, and snippets.

@chaddotson
Created October 20, 2013 21:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chaddotson/7075299 to your computer and use it in GitHub Desktop.
Save chaddotson/7075299 to your computer and use it in GitHub Desktop.
A code snippet that allows arbitrary code to be executed given a set of inputs. The expected outputs will be returned.
def exec_code(code, inputs, outputs):
"""Execute the provided code given the inputs, return a dictonary of the outputs.
Keyword arguments:
code -- the python code to run.
inputs -- a dictionary of variable/initial values.
outputs -- the list of output variables to preserve from the run.
"""
for variable, value in inputs.items():
exec(variable + '=' + str(value))
for variable in outputs:
exec(variable + '=' + str('0'))
exec code
results = {}
for variable in outputs:
results[variable] = locals().get(variable, None)
return results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment