Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a particular Python function in C# with IronPython

So far I have a simple class that wraps a python engine (IronPython) for my use. Although code looks big it's really simple so I copy it here to be more clear with my issue.

Here's the code:

public class PythonInstance
{
    ScriptEngine engine;
    ScriptScope scope;
    ScriptSource source;

    public PythonInstance()
    {
        engine = Python.CreateEngine();
        scope = engine.CreateScope();
    }

    public void LoadCode(string code)
    {
        source = engine.CreateScriptSourceFromString(code, Microsoft.Scripting.SourceCodeKind.Statements);
        source.Compile();
    }

    public void SetVariable(string key, dynamic variable)
    {
        scope.SetVariable(key, variable);
    }

    public void RunCode()
    {
        source.Execute(scope);
    }

    public void CallFunction(string function)
    {
        //?????? no idea what to call here
    }

}

So, it works great but it only allows me to execute all python script at once... but what I would like to do is to be able to call particular functions from within a pythos script.

So, my question: How do I call particular function in the loaded script?

I was trying to find some information or tutorials but unfortunately couldn't find anything.

like image 990
NewProger Avatar asked Jan 03 '13 13:01

NewProger


1 Answers

You can use ScriptScope.GetVariable to get the actual function and then you can call it like a c# function. Use it like this: C# code:

var var1,var2=...
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
engine.ExecuteFile(@"C:\test.py", scope);
dynamic testFunction = scope.GetVariable("test_func");
var result = testFunction(var1,var2);

Python code:

def test_func(var1,var2):
    ...do something...

Took me a while to finally figure it out, and it's quite simple.. Too bad there's no good IronPython documentation. Hope this helps :)

like image 140
LiRoN Avatar answered Sep 22 '22 11:09

LiRoN