簡體   English   中英

在Python中動態生成/創建函數

[英]Dynamically generate/create a function in 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__

但我仍然得到:'模塊'對象沒有屬性'execCodeSnippet'

這是我設法做到的方式(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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM