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

2024-09-30 16:38:49 发布

您现在位置: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文件中修改哪些值。在

编辑: 我也试过了

^{pr2}$

但我仍然得到:“module”对象没有属性“execcodesippet”


Tags: 函数insavedeflineexecprintsavefile
1条回答
网友
1楼 · 发布于 2024-09-30 16:38:49

下面是我如何做到的(Python3):

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)

相关问题 更多 >