当前位置:首页 > 通信资讯 > 正文

C#调用python脚本(c#如何调用python代码)

ironpython是一种在 .net及 mono上的 python实现,由微软的 jim hugunin所发起,是一个开源的项目,基于微软的 dlr引擎。ironpython的在codeplex上的主页:http://ironpython.codeplex.com/

使用场景:

如果你的小伙伴会写python脚本,而且已经实现大部分项目的功能不需要再用c# 实现。现在缺少窗体,此时python+c#的组合就可以完美的结局问题啦!

示例:
借由ironpython,就可以利用.net执行存储在python脚本中的代码段。下面通过简单的示例说明如何应用c#调用python脚本。

1、在vs中新建窗体项目:ironpythondemo

2、vs的菜单中打开“nuget程序包管理器”

C#调用python脚本(c#如何调用python代码)

3、搜索ironpython程序包并安装

C#调用python脚本(c#如何调用python代码)

4、在exe程序所在文件夹下(此例中为".\ironpythondemo\ironpythondemo\bin\debug"),创建python脚本。或将现有的脚本拷贝到该目录下。python示例脚本实现求两个数的四则运算:

?
1 2 3 4 5 6 7 8 9 10 11 num1=arg1 num2=arg2 op=arg3 if op==1: result=num1+num2 elif op==2: result=num1-num2 elif op==3: result=num1*num2 else: result=num1*1.0/num2

5、修改工程的配置文件app.config如下:
其中microsoft.scripting节点中设置了ironpython语言引擎的几个属性。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 <?xml version="1.0" encoding="utf-8" ?> <configuration> <configsections> <section name="microsoft.scripting" type="microsoft.scripting.hosting.configuration.section, microsoft.scripting"/> </configsections> <microsoft.scripting> <languages> <language names="ironpython;python;py" extensions=".py" displayname="python" type="ironpython.runtime.pythoncontext, ironpython"/> </languages> </microsoft.scripting> <startup> <supportedruntime version="v4.0" sku=".netframework,version=v4.5" /> </startup> </configuration>

6、 绘制窗体如下:

C#调用python脚本(c#如何调用python代码)

7、编写计算的函数:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 private void btncalculate_click(object sender, eventargs e) { scriptruntime scriptruntime = scriptruntime.createfromconfiguration(); scriptengine rbeng = scriptruntime.getengine("python"); scriptsource source = rbeng.createscriptsourcefromfile("ironpythondemo.py");//设置脚本文件 scriptscope scope = rbeng.createscope(); try { //设置参数 scope.setvariable("arg1",convert.toint32(txtnum1.text)); scope.setvariable("arg2", convert.toint32(txtnum2.text)); scope.setvariable("arg3", operation.selectedindex+1); } catch (exception) { messagebox.show("输入有误。"); } source.execute(scope); labelresult.text = scope.getvariable("result").tostring(); }

8、编译运行可得计算结果(此处未做输入的检查)

C#调用python脚本(c#如何调用python代码)

以上就是c#调用python脚本的简单方法,希望对大家的学习有所帮助。

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。