如何调用从一个Python脚本在C#中的特定方法? [英] How do I call a specific Method from a Python Script in C#?
本文介绍了如何调用从一个Python脚本在C#中的特定方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道是否有可能调用从一个Python脚本的具体方法在C#项目。
I'm wondering if there is a possibility to call a specific Method from a Python script over a C# project.
我没有code ...但我的想法是:
I have no code... but my idea is:
Python的code:
Python Code:
def SetHostInfos(Host,IP,Password):
Work to do...
def CalcAdd(Numb1,Numb2):
Work to do...
C#code:
C# Code:
SetHostInfos("test","0.0.0.0","PWD")
result = CalcAdd(12,13)
我怎么能调用的方法之一,从这个Python脚本,在C#?
How can I call one of the Methods, from this Python script, over C#?
推荐答案
您可以承载的IronPython,执行脚本,并通过创建范围访问脚本中定义的功能。
You can host IronPython, execute the script and access the functions defined within the script through the created scope.
下面的示例显示了基本概念和使用功能从C#两种方式。
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
这篇关于如何调用从一个Python脚本在C#中的特定方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文