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

旧巷老猫 提交于 2019-11-27 12:11:18
Simon Opelt

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

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.7\Lib", "bar"};

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

Python_File.MethodCall("test");

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:

#!/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 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

Paul Collingwood

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#? http://blogs.msdn.com/b/charlie/archive/2009/10/25/hosting-ironpython-in-a-c-4-0-program.aspx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!