gpt4 book ai didi

c# - 将变量从 C# - IronPython 传递到 Python 脚本

转载 作者:太空宇宙 更新时间:2023-11-03 16:49:26 25 4
gpt4 key购买 nike

我有一个 WPF 应用程序。出于这个问题的目的,我们假设它是一个带有按钮的简单窗口。当我单击该按钮时,我希望执行一个 Python 脚本。因此,我环顾四周,发现我可以使用 IronPython 运行 Python 脚本。 第 1 部分 运行良好,它运行 python 脚本。根据我在网络上收集的信息,如果我想调用特定方法,第 2 部分是我应该做的。

private void btnWhatever_Click(object sender, RoutedEventArgs e)
{
//Basic engine to run python script. - Part1
ScriptEngine engine = Python.CreateEngine();
string pythonScriptPath = System.IO.Path.GetDirectoryName(System.IO.Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));
ScriptSource source = engine.CreateScriptSourceFromFile(pythonScriptPath + "/python.py");
ScriptScope scope = engine.CreateScope();
source.Execute(scope);

//Part2
Object myclass = engine.Operations.Invoke(scope.GetVariable("pythonScriptClass"));
object[] parameters = new object[] { "Hi",3 };
engine.Operations.InvokeMember(myclass, "theMethod", parameters);
}

问题是,我一直在 Microsoft.Dynamic.dll 中发生 'Microsoft.Scripting.ArgumentTypeException' :theMethod() 恰好需要 2 个参数(给定 3 个参数) .

我从这个错误中了解到,我给出了 3 个参数而不是 2 个,但我无法根据我发现的情况以另一种方式调用特定方法。一般来说,我对 IronPython 和 Python 还很陌生,但这里有一个脚本示例:

class pythonScriptClass:

def swapText(text, number):
return text[number:] + text[:number]

def getLetterIndex(letter, text):
for k in range(len(text)):
if (letter== text[k]):
return k
return -1

def theMethod(text , number):
result= swapText("textToBeSwaped", number)
toBeReturned = ""
for letter in text:
if letter in "abcdefghijklmnopqrstuvwxyz":
toBeReturned = toBeReturned + result[getLetterIndex(letter, result)]
return toBeReturned

我目前的最终目标是让它工作,因此能够从 Python 脚本调用 theMethod() 并使用 C# - IronPython 获取返回值。

我尝试过其他方法,例如:scope.SetVariable("key","value");但我遇到了同样的错误。

最佳答案

对于Python成员方法,第一个参数是self

class pythonScriptClass:
def theMethod(self, text, number):
# and call self.swapText(...)

这就是参数数量出错的原因。

关于c# - 将变量从 C# - IronPython 传递到 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36002844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com