在.net程序中使用IronPython引擎
有时候,业务规则相对比较灵活多变,如果可以使用脚本对这样的规则进行处理,运行时动态调用则会增加一些程序的灵活性。IronPython给了我们这样的能力。下面的例子可以动态执行一个叫做foo.py的python程序,并且程序可以改变传入的.net对象(作为输出结果)
1 using System;
2 using IronPython.Hosting;
3
4 namespace IronPythonHostingDemo
5 {
6 class ClassA
7 {
8 private int value;
9
10 public ClassA()
11 {
12 this.value = 1;
13 }
14
15 public int Value
16 {
17 get { return value; }
18 set { this.value = value; }
19 }
20 }
21
22 class DemoProgram
23 {
24 static void ProcessByPython(ClassA a)
25 {
26 PythonEngine engine = new PythonEngine();
27 EngineModule em = engine.CreateModule("foo", false);
28
29 em.Globals["objectA"] = a;
30
31 engine.ExecuteFile("foo.py", em);
32 }
33
34 static void Main(string[] args)
35 {
36 try
37 {
38 ClassA a = new ClassA();
39 ProcessByPython(a);
40 Console.WriteLine("a.value = " + a.Value);
41 }
42 catch (Exception e)
43 {
44 Console.WriteLine(e);
45 }
46 }
47 }
48 }
49
2 using IronPython.Hosting;
3
4 namespace IronPythonHostingDemo
5 {
6 class ClassA
7 {
8 private int value;
9
10 public ClassA()
11 {
12 this.value = 1;
13 }
14
15 public int Value
16 {
17 get { return value; }
18 set { this.value = value; }
19 }
20 }
21
22 class DemoProgram
23 {
24 static void ProcessByPython(ClassA a)
25 {
26 PythonEngine engine = new PythonEngine();
27 EngineModule em = engine.CreateModule("foo", false);
28
29 em.Globals["objectA"] = a;
30
31 engine.ExecuteFile("foo.py", em);
32 }
33
34 static void Main(string[] args)
35 {
36 try
37 {
38 ClassA a = new ClassA();
39 ProcessByPython(a);
40 Console.WriteLine("a.value = " + a.Value);
41 }
42 catch (Exception e)
43 {
44 Console.WriteLine(e);
45 }
46 }
47 }
48 }
49
对应的foo.py如下:
1 def foo(a):
2 a.Value = a.Value * 2
3
4 foo(objectA)
2 a.Value = a.Value * 2
3
4 foo(objectA)
程序都很简单,我就不多废话了。
posted on 2006-12-27 14:28 iceboundrock 阅读(529) 评论(1) 编辑 收藏 举报