您的位置:首页 > 编程语言 > Python开发

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

2015-07-07 16:20 841 查看
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、编译运行可得计算结果(此处未做输入的检查)
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python c#