好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#调用Python脚本的简单示例

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

使用场景:

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

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

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

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

3、搜索ironpython程序包并安装

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

?

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语言引擎的几个属性。

?

<? 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、 绘制窗体如下:

7、编写计算的函数:

?

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脚本的简单方法,希望对大家的学习有所帮助。

dy("nrwz");

查看更多关于C#调用Python脚本的简单示例的详细内容...

  阅读:50次