I have a WPF application. For the purpose of this question, let's say it's a simple Window with a button. When I click on that button, I would like a Python script to be executed. Therefore, I went looking around and found out that I can run Python scripts using IronPython. Part1 works well, it runs the python scripts. From what I've gathered from looking around the web, Part2 is what I should do if I want to call a specific method.
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);
}
The problem is, I kept getting 'Microsoft.Scripting.ArgumentTypeException' happened in Microsoft.Dynamic.dll : theMethod() takes exactly 2 arguments (3 given).
I understand from that error that I'm giving 3 arguments instead of 2 but I can't call a specific method another way from what I found out. I'm pretty new to IronPython and Python in general but here is a script example :
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
My ultimate goal for the moment is to get this to work and therefore be able to call theMethod() from the Python script and get the returned value using C# - IronPython.
I have tried other methods such as : scope.SetVariable("key","value"); but I got the same error.
object[] parameterswithnew object[] { "Hi",3 }is interpreted in Python? It looks 2-length but treated as 3-length, possibly "H", "i" and "3"? What happens with{"foo", 3}?