什么是IronPython?
IronPython 是一种在 NET 和 Mono 上实现的 Python 语言,由 Jim Hugunin(同时也是 Jython 创造者)所创造,2006年9月5日首次发布。随后,在 2007 年,开发者决定改写构架,使用动态类型系统以让更多脚本语言能很容易地移植到NET Framework上。2008 年,随着微软发布 NET Framework3.0/3.5、Silverlight 之后,IronPython也发布了 2.0 版,最新版本是 2.7,于 2011年3月发布,支持.NET Framework 4.0。来自百度词条,其中最新版本不是2.7,现已支持.NET Framework 4.6以上的3.4版本。
为什么要用IronPython?
从两个优秀的世界各取所长,更高效的复用代码,那可简直太棒啦!通过使用IronPython 运行时库,你可以让Python脚本运行在你的.NET程序中。
操作步骤,首先从NuGet解决方案中为项目安装IronPython。

然后添加引用即可。
C#WinForm界面上布置botton和textbox各一个,代码如下:
using System;using System.Windows.Forms;using IronPython.Hosting;using Microsoft.Scripting.Hosting;namespace IronPython{public partial class Form1 : Form{public Form1(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){var engine = IronPython.Hosting.Python.CreateEngine();var scope = engine.CreateScope();var source = engine.CreateScriptSourceFromFile("hello.py");source.Execute(scope);var add = scope.GetVariable<Func<object, object, object>>("add");var result1 = add(1, 2);var say_hello = scope.GetVariable<Func<object>>("say_hello");var result2=say_hello();var get_text = scope.GetVariable<Func<object>>("get_text");var result3 = get_text().ToString();textBox1.Text = result1.ToString()+ "\r\n" + result2+ "\r\n" + result3;}}}
在该解决方案\bin\Debug目录下创建hello.py,代码为:
def say_hello():return "Hello!"def get_text():return "text from hello.py"def add(arg1,arg2):return arg1+arg2

运行结果如图,这样即完成调用,导入的如果是内置模块的话,一般都是很顺利的,如果你试试import第三方模块呢?你看看它会正常运行吗?可以尝试一下解决,下一节仔细解释。
今日推荐:正版入门书籍,点击下方链接拼团购买。
文章转载自工业解决方案,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




