如何从C#中的Python脚本调用特定方法?

Van*_*ath 16 c# python methods ironpython arguments

我想知道是否有可能通过C#项目从Python脚本调用特定的方法.

我没有代码......但我的想法是:

Python代码:

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

def CalcAdd(Numb1,Numb2):
   Work to do...
Run Code Online (Sandbox Code Playgroud)

C#代码:

SetHostInfos("test","0.0.0.0","PWD")
result = CalcAdd(12,13)
Run Code Online (Sandbox Code Playgroud)

如何通过C#调用此Python脚本中的一个方法?

Sim*_*elt 24

您可以托管IronPython,执行脚本并通过创建的范围访问脚本中定义的功能.

以下示例显示了使用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
Run Code Online (Sandbox Code Playgroud)


Van*_*ath 5

我发现了一种类似的方法,该方法的调用要容易得多。

C#代码如下:

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");
Run Code Online (Sandbox Code Playgroud)

因此,基本上我提交了带有库路径的字典,该路径要在我的python文件中定义。

因此,PYthon脚本如下所示:

#!/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
Run Code Online (Sandbox Code Playgroud)

因此,现在使用C#可以更轻松地进行方法调用,并且参数传递保持不变。同样,通过此代码,您可以获取Python文件的自定义库文件夹,如果您在具有许多不同PC的网络中工作,这将非常好