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

Posted on

Question :

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:

result = CalcAdd(12,13)

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

Asked By: VanDeath


Answer #1:

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
Answered By: Simon Opelt

Answer #2:

I found a similar way to do it, the call of the method is much easier with it.

C# Code goes as follows:

IDictionary<string, object> options = new Dictionary<string, object>();
options["Arguments"] = new [] {"C:Program Files (x86)IronPython 2.7Lib", "bar"};

var ipy = Python.CreateRuntime(options);
dynamic Python_File = ipy.UseFile("");


So basically I submit the Dictionary with the Library path which I want to define in my python file.

So the PYthon Script looks as follows:


import sys
path = sys.argv[0]  #1 argument given is a string for the path
import httplib
import urllib
import string

def MethodCall(OutputString):
    print Outputstring

So The method call is now much easier from C#
And the argument passing stays the same.
Also with this code you are able to get a custom library folder
for the Python file which is very nice if you work in a network
with a lot of different PC’s

Answered By: VanDeath

Answer #3:

You could make your python program take arguments on the command line then call it as a command line app from your C# code.

If that’s the way to go then there are plenty of resources:

How do I run a Python script from C#?

Answered By: Paul Collingwood

Leave a Reply

Your email address will not be published. Required fields are marked *