在C#环境中动态调用IronPython脚本(一)

it2022-05-24  67

   本文讲述用C#调用Ironpython运行环境,解析并运行动态pyhton脚本。这种情况应用在那些需要滞后规定行为的场合,例如,动态计算项(计算引擎),用户可以自定义计算内容、计算公式等。

        本文的代码适用于IronPython 2.7(需要下载及安装)及C#4.0,由于IronPython早期版本提供的Hosting API不同,对于网上搜索得到的代码,如果是早期版本代码(多数如此),并不能编译通过,所以本文强调代码的版本问题。

        本文代码需要引用两个命名空间IronPython和Microsoft.Scripting (文件位置分别为IronPython 2.7的安装目录下的IronPython.dll和Microsoft.Scripting.dll)。 

一、最简单的例子

        先看一个最简单的例子,C#环境与Python环境没有数据联系。       

[csharp]  view plain  copy   public static void test1()  {        var engine = IronPython.Hosting.Python.CreateEngine();        engine.CreateScriptSourceFromString("print 'hello world'").Execute();        Console.ReadLine();  }  

        如果IronPython环境建立好,运行test1(),就会得到正确的结果。如果只想运行一段脚本,就是这般简单。

二、C#环境调用Python环境函数

        以上的例子没有实用价值,再看第二个例子,这个例子演示了如何从C#环境调用Python环境中的函数以及类中方法。

[csharp]  view plain  copy   public static void test2()         {             var engine = Python.CreateEngine();             var scope = engine.CreateScope();             var source = engine.CreateScriptSourceFromString(                 "def adder(arg1, arg2):\n" +                 "   return arg1 + arg2\n" +                 "\n" +                 "def fun(arg1):\n" +                 "   tel = {'jack': 4098, 'sape': 4139}\n" +                 "   for k, v in arg1.iteritems():\n"+                 "      tel[k]=v\n"+                 "   return tel\n" +                 "\n" +                 "class MyClass(object):\n" +                 "   def __init__(self, value):\n" +                 "       self.value = value\n");             source.Execute(scope);               var adder = scope.GetVariable<Func<object, object, object>>("adder");             Console.WriteLine(adder(2, 2));               var fun = scope.GetVariable<Func<object, object>>("fun");             IronPython.Runtime.PythonDictionary inputDict = new IronPython.Runtime.PythonDictionary();             inputDict["abc"] = "abc";             inputDict["def"] = 456;             object res = fun(inputDict);             IronPython.Runtime.PythonDictionary outputDict = res as IronPython.Runtime.PythonDictionary;             foreach (var k in outputDict.Keys)             {                 Console.WriteLine("key:"+ k.ToString()+" val:  " + outputDict[k].ToString());             }               var myClass = scope.GetVariable<Func<object, object>>("MyClass");             var myInstance = myClass("hello");               Console.WriteLine(engine.Operations.GetMember(myInstance, "value"));         }  

上面代码中,python中有两个函数和一个类,第一个函数的参数是简单数据类型,第二个是复杂数据类型(关于两个环境下复杂数据类型的对应,下面将论述)。无论是类还是函数,C#的调用方法都是通过ScriptScope.GetVariable,它的函数定义如下:

T GetVariable<T>(string name);

ScriptScope还有一个更“安全”的方法

boolTryGetVariable<T>(string name, out T value);

可以完成相似的操作。

这个例子,可以扩展C#的应用,例如,python有丰富的数学计算库,而C#在这方面较欠缺,这时,就可以采用上面的方式,计算部分采用现成的python库,而主控程序采用C#编制。

三、在Python环境中调用C#环境函数

现在看第三个例子,如果Python运行逻辑复杂,需要在运行过程中调用C#函数怎么办?

 

[csharp]  view plain  copy   public static void test3()          {              var engine = Python.CreateEngine();              var scope = engine.CreateScope();                scope.SetVariable("my_object_model", new CSharpClass ());              string pythonscript =                  "def fun(arg1):\n" +                  "   result = arg1+1\n" +                  "   return result\n" +                  "adder = fun(5) + my_object_model.Foo(2)\n" ;               engine.CreateScriptSourceFromString(pythonscript).Execute(scope);               Console.WriteLine(scope.GetVariable("adder"));          }  Class CSharpClass  {          public int Foo(int arg)          {             return  arg +1;          }  }  

 

这个例子中,创建CShparpClass类,并将其作为“变量”传到Python环境中,在Python中就可以调用了。注意到C#中的类名可以和Python中不一样。

 

 

四、在Python环境中动态调用C#库

        在这种情况下,Python脚本和C#库都是“滞后”于主应用才编写出来的,可以满足用户现场定制行为(采用Python脚本),并且可以给Python脚本传入现场定制的参数。

首先,建立一个C#库,代码如下:

 

[csharp]  view plain  copy   namespace LibforPython  {      public class PythonLib      {          public int Test(int x, string op)          {              switch (op.ToUpper())              {                  case "INC":                      return x + 1;                  case "DEC":                      return x - 1;              }              return x + 1;          }      }  }  

编译成LibforPython.dll后拷贝到主运行程序的运行目录(二者同目录)。调用代码如下:

 

[csharp]  view plain  copy   public static void test4()    {        var engine = Python.CreateEngine();        var scope = engine.CreateScope();        engine.Runtime.LoadAssembly(Assembly.LoadFrom("LibforPython.dll"));              string pythonscript =           "from LibforPython import PythonLib\n" +           "o = PythonLib()\n" +           "res = o.Test(6,'add')\n";        engine.CreateScriptSourceFromString(pythonscript).Execute(scope);        Console.WriteLine(scope.GetVariable("res"));    }  

 

运行以上程序即可。这个例子中,LibforPython.dll是在运行时才引入Python环境中的。对于预先已知的Python可能用到的接口,才用例三的办法更好些,对于预先无法预先定义或“遗忘”的接口,采用本例比较适合。

 

五、总结

    将Python环境“寄宿”于C#环境,进而动态执行用户自定义的脚本,是应用可配置性、灵活性的一种体现(其他动态语言也可以这么做,以Ironpython比较简单)。这一过程包括以下三步:

           var engine = Python.CreateEngine();

           var scope = engine.CreateScope();

           var source = engine.CreateScriptSourceFromString(“…”);

           source.Execute(scope);

Python环境与宿主环境的交互(参数传入、传出),则通过ScriptScop的GetVariable和SetVariable进行。

转载于:https://www.cnblogs.com/mschen/p/5349546.html

相关资源:在VS2017中用C#调用python脚本的实现

最新回复(0)