龙空技术网

C#访问python文件函数接口

横晓天下 183

前言:

现在咱们对“cmd 调用python”都比较讲究,看官们都需要学习一些“cmd 调用python”的相关资讯。那么小编同时在网络上汇集了一些对于“cmd 调用python””的相关资讯,希望朋友们能喜欢,看官们快快来学习一下吧!

C#与python进行交互的方式有很多,有人利用C++程序调用python,然后封装成动态链库(dll),提供给C#调用;也可以利用C#命令行调用python,即通过python.exe执行.py文件,第三种方式就是利用IronPython实现与python的交互。

IronPython的使用:

1)到NuGet安装IronPython,如图:

2)添加IronPython的相关引用,如图:

3)将.py文件放到C#项目Debug目录下,如下图:

4)编辑C#代码:

var path = AppDomain.CurrentDomain.BaseDirectory + "pyCaldemo.py";

//方法一:

//ScriptRuntime pyRuntime = Python.CreateRuntime();

//dynamic func = pyRuntime.UseFile(path);//.py路径

//var result = func.Add(this.num_f1.Value, this.num_f2.Value)

//方法二:

//ScriptEngine engine = Python.CreateEngine();

//dynamic func = engine.ExecuteFile(path);

//var result = func.Add(this.num_f1.Value, this.num_f2.Value);

//方法三:

ScriptEngine engine = Python.CreateEngine();

ScriptScope scope = engine.CreateScope();

ScriptSource script = engine.CreateScriptSourceFromFile(path);

script.Compile().Execute(scope);

var _func = scope.GetVariable("Add");

var result = _func(this.num_f1.Value, this.num_f2.Value);

4)执行结果:

标签: #cmd 调用python