在Python中动态生成/创建函数

时间:2015-10-30 08:48:10

标签: python

我试图在Python中动态创建一个函数并执行它。这就是我到目前为止所做的:

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)

我已经读过exec应该在当前命名空间中创建函数,但它不会。接下来我需要做什么? 我试图在字典中执行它,但它返回一个空字符。

我们的想法是让用户定义在Json文件中修改的值。

编辑: 我也试过这个

    module = imp.new_module('codesnippets')
    exec(dynamicFunction) in module.__dict__

但我仍然得到:'module'对象没有属性'execCodeSnippet'

1 个答案:

答案 0 :(得分:0)

以下是我设法做到的方法(Python 3):

def ExecuteScript(saveFile, updatedSaveFile, codeSnippet ):
    decryptedData, jsonData = FixSave.GetDataFromSaveFile(saveFile)
    FixSave.Save(decryptedData, jsonData, updatedSaveFile + "_original")

    dynamicFunction = ""
    dynamicFunction += "def execCodeSnippet(json_data):\n"
    for line in codeSnippet.splitlines():
        line = "    " + line.strip() + "\n"
        dynamicFunction += line
    dynamicFunction += "    return json_data\n"

    module = imp.new_module('codesnippets')
    exec(dynamicFunction, module.__dict__)

    jsonDataFixed = module.execCodeSnippet(jsonData)

    FixSave.Save(decryptedData, jsonDataFixed, updatedSaveFile)