How do I call a specific Method from a Python Script in C#?

VanDeath picture VanDeath · Nov 5, 2012 · Viewed 25.7k times · Source

I'm wondering if there is a possibility to call a specific Method from a Python script over a C# project.

I have no code... but my idea is:

Python Code:

def SetHostInfos(Host,IP,Password):
   Work to do...

def CalcAdd(Numb1,Numb2):
   Work to do...

C# Code:

SetHostInfos("test","0.0.0.0","PWD")
result = CalcAdd(12,13)

How can I call one of the Methods, from this Python script, over C#?

Answer

Simon Opelt picture Simon Opelt · Nov 5, 2012

You can host IronPython, execute the script and access the functions defined within the script through the created scope.

The following sample shows the basic concept and two ways of using the function from C#.

var pySrc =
@"def CalcAdd(Numb1, Numb2):
    return Numb1 + Numb2";

// host python and execute script
var engine = IronPython.Hosting.Python.CreateEngine();
var scope = engine.CreateScope();
engine.Execute(pySrc, scope);

// get function and dynamically invoke
var calcAdd = scope.GetVariable("CalcAdd");
var result = calcAdd(34, 8); // returns 42 (Int32)

// get function with a strongly typed signature
var calcAddTyped = scope.GetVariable<Func<decimal, decimal, decimal>>("CalcAdd");
var resultTyped = calcAddTyped(5, 7); // returns 12m