Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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#?

like image 403
VanDeath Avatar asked Nov 05 '12 12:11

VanDeath


People also ask

Can I call a Python function in C?

We can call a C function from Python program using the ctypes module.

How do you call a Python script in C?

The first step towards embedding Python in C is to initialize Python interpreter, which can be done with the following C function. Py_Initialize(); After the interpreter is initialized, you need to set the path to the Python module you would like to import in your C program.

How do you call a function in Python script?

To use functions in Python, you write the function name (or the variable that points to the function object) followed by parentheses (to call the function). If that function accepts arguments (as most functions do), then you'll pass the arguments inside the parentheses as you call the function.


1 Answers

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
like image 162
Simon Opelt Avatar answered Oct 12 '22 22:10

Simon Opelt