How can I call a specific method from Python Script in C #?

I am wondering if it is possible to call a specific method from a Python script on 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 #?

+10
python methods c # arguments ironpython
source share
3 answers

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

The following example shows a basic concept and two ways to use a 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 
+17
source share

You can force your python program to accept arguments on the command line and then call it as a command line application from your C # code.

If so, then there are many resources:

How to run Python script with C #? http://blogs.msdn.com/b/charlie/archive/2009/10/25/hosting-ironpython-in-ac-4-0-program.aspx

+1
source share

I found a similar way to do this, calling a method is much easier with it.

C # code is as follows:

 IDictionary<string, object> options = new Dictionary<string, object>(); options["Arguments"] = new [] {"C:\Program Files (x86)\IronPython 2.7\Lib", "bar"}; var ipy = Python.CreateRuntime(options); dynamic Python_File = ipy.UseFile("test.py"); Python_File.MethodCall("test"); 

So basically I am sending the dictionary using the library path that I want to define in my python file.

So PYthon Script looks like this:

 #!/usr/bin/python import sys path = sys.argv[0] #1 argument given is a string for the path sys.path.append(path) import httplib import urllib import string def MethodCall(OutputString): print Outputstring 

So method invocation is now much easier with C # and passing arguments remains unchanged. Also with this code you can get a user library folder for a Python file, which is very good if you work on a network with a lot of different PCs

+1
source share

All Articles