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程序包管理器”

 


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、编译运行可得计算结果(此处未做输入的检查)

 
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值