IronPython是Python编程语言的一种开源实现,它可以与.NET Framework框架紧密集成。IronPython可使用.NET Framework和Python标准类库,而.NET语言也能够很简单地使用Python代码。python
使用Visual Studio建立一个单元测试项目,添加Microsoft.CSharp.dll的引用,经过Nuget添加IronPython包,在项目中添加下面代码,运行单元测试。编程
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTestProjectIronPython { [TestClass] public class UnitTest1 { //基本用法 [TestMethod] public void TestMethod1() { //建立脚本引擎 var engine = IronPython.Hosting.Python.CreateEngine(); //编写脚本 var pythonScript = "1+1"; //经过引擎执行脚本 var sum = engine.Execute<int>(pythonScript); //判断c#中执行和IronPython中执行结果是否相等 Assert.AreEqual(1 + 1, sum); } //传入变量 [TestMethod] public void TestMethod2() { //建立脚本引擎 var engine = IronPython.Hosting.Python.CreateEngine(); //经过引擎建立做用域 var scope = engine.CreateScope(); //建立变量 var a = 1; var b = 2; //在做用域中设置变量 scope.SetVariable("a", a); scope.SetVariable("b", b); //待执行脚本 var pythonScript = "a+b"; //经过引擎建立脚本源 var scriptSource = engine.CreateScriptSourceFromString(pythonScript); //在做用域上执行脚本源 var sum = scriptSource.Execute<int>(scope); //判断c#中执行和IronPython中执行结果是否相等 Assert.AreEqual(a + b, sum); } //传入函数 [TestMethod] public void TestMethod3() { //建立脚本引擎 var engine = IronPython.Hosting.Python.CreateEngine(); //经过引擎建立做用域 var scope = engine.CreateScope(); //建立函数 Func<int,int> fn = (i) => i * i; //在做用域中设置变量 scope.SetVariable("fn", fn); //待执行脚本 var pythonScript = "fn(4)"; //在做用域上执行脚本源 var scriptSource = engine.CreateScriptSourceFromString(pythonScript); //在做用域上执行脚本源 var result = scriptSource.Execute<int>(scope); //判断c#中执行和IronPython中执行结果是否相等 Assert.AreEqual(fn(4), result); } //IronPython定义函数,.NET调用 [TestMethod] public void TestMethod4() { //建立脚本引擎 var engine = IronPython.Hosting.Python.CreateEngine(); //编写脚本 var pythonScript = "lambda x:x*x"; //动态类型访问python对象 dynamic result = engine.Execute(pythonScript); //判断c#中执行和调用IronPython执行结果是否相等 Assert.AreEqual(4 * 4, result(4)); } //编译运行 [TestMethod] public void TestMethod5() { //建立脚本引擎 var engine = IronPython.Hosting.Python.CreateEngine(); //经过引擎建立做用域 var scope = engine.CreateScope(); //建立函数 Func<int, int> fn = (i) => i * i; //在做用域中设置变量 scope.SetVariable("fn", fn); //待执行脚本 var pythonScript = "fn(4)"; //在做用域上执行脚本源 var scriptSource = engine.CreateScriptSourceFromString(pythonScript); //编译脚本源 var compileCode = scriptSource.Compile(); //在做用域上执行脚本源 var result = compileCode.Execute<int>(scope); //判断c#中执行和IronPython中执行结果是否相等 Assert.AreEqual(fn(4), result); } } }