如何从 C# 中的 Python 脚本调用特定方法? [英] How do I call a specific Method from a Python Script in C#?

查看:17
本文介绍了如何从 C# 中的 Python 脚本调用特定方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm wondering if there is a possibility to call a specific Method from a Python script over a C# project.

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

I have no code... but my idea is:

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 脚本调用其中一种方法?

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

这篇关于如何从 C# 中的 Python 脚本调用特定方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆