I am trying to dynamically create a function in Python and execute it. This is what I have so far:
def ExecuteScript(saveFile, updatedSaveFile, codeSnippet ):
decryptedData, jsonData = FixSave.GetDataFromSaveFile(saveFile)
FixSave.Save(decryptedData, jsonData, updatedSaveFile + "_original")
dynamicFunction = ""
dynamicFunction += "def execCodeSippet(jsonData):\n"
for line in codeSnippet.splitlines():
line = " " + line.strip() + "\n"
dynamicFunction += line
dynamicFunction += " return jsonData\n"
#execCodeSnippetD = {}
exec(dynamicFunction) # in execCodeSnippetD
#print(execCodeSnippetD)
#exec("print(execCodeSnippetD)")
jsonData = execCodeSnippet(jsonData)
FixSave.Save(decryptedData, jsonData, updatedSaveFile)
I've read that exec should create the function in the current namespace but it wouldn't. What do I need to do next? I have tried to execute it in a dictionary but it returns an empty one.
The idea is to let the user define what values are modified in a Json file.
Edit: I tried this too
module = imp.new_module('codesnippets')
exec(dynamicFunction) in module.__dict__
but I still get: 'module' object has no attribute 'execCodeSnippet'