【问题标题】:How do I call a specific Method from a Python Script in C#?如何从 C# 中的 Python 脚本调用特定方法?
【发布时间】:2012-10-25 06:39:24
【问题描述】:

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

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

Python 代码:

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

def CalcAdd(Numb1,Numb2):
   Work to do...

C#代码:

SetHostInfos("test","0.0.0.0","PWD")
result = CalcAdd(12,13)

如何通过 C# 从这个 Python 脚本调用其中一种方法?

【问题讨论】:

标签: c# python methods arguments ironpython


【解决方案1】:

您可以托管 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

【讨论】:

    【解决方案2】:

    我找到了类似的方法,方法的调用更容易。

    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");
    

    所以基本上我提交了带有我想在我的 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
    

    所以现在从 C# 中调用方法要容易得多 并且参数传递保持不变。 同样使用此代码,您可以获得自定义库文件夹 对于 Python 文件,如果您在网络中工作,这非常好 有很多不同的电脑

    【讨论】:

      【解决方案3】:

      您可以让您的 python 程序在命令行上接受参数,然后从您的 C# 代码中将其作为命令行应用程序调用。

      如果这是要走的路,那么有很多资源:

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-14
        • 2012-08-23
        • 2014-04-21
        • 1970-01-01
        • 1970-01-01
        • 2017-11-02
        • 2014-06-25
        • 1970-01-01
        相关资源
        最近更新 更多