在.net程式中使用IronPython引擎

來源:互聯網
上載者:User

有時候,商務規則相對比較靈活多變,如果可以使用指令碼對這樣的規則進行處理,運行時動態調用則會增加一些程式的靈活性。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 

對應的foo.py如下:

1 def foo(a):
2     a.Value = a.Value * 2

4 foo(objectA)

程式都很簡單,我就不多廢話了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.