在第一篇中只是簡單的建立了一個互動環境,這樣還達不到我的目標,為了將python整合進應用,還需要讓python和我們的.net應用互相可以訪問.
在IronPython Alpha1中,是有一個CHM文檔的,下載了正式版之後,居然找不到了...在maillist中問了之後才知道, 原來搞了份DOC檔,放在http://dlr.codeplex.com/. 下載之後才發現是專門講HOST的,真爽(下載頁面看這裡).
今天的任務比較簡單, 向python引擎中放一個簡單變數a, 然後用python修改它, 再讀回來,代碼如:
public void Run1() { helper.DefaultScope.SetVariable("a", 1); helper.Execute("print 'visit a in python: ', a"); helper.Execute("print 'modify a into 2'"); helper.Execute("a=2"); object a = helper.DefaultScope.GetVariable("a"); helper.PrintLn("get a from python", a); }
helper是自己整理了一個專門用於初始化環境並執行python語句的類,以後希望可以逐步整理,並用在以後的應用中.代碼如下:
using System;using System.Collections.Generic;using System.Text;using Microsoft.Scripting.Hosting;using IronPython.Hosting;namespace AccessEach { /// /// IronPython Helper /// public sealed class IPHelper { #region private private IPHelper() { _defaultEngine = Python.CreateEngine(); _defaultScope = _defaultEngine.CreateScope(); } private ScriptEngine _defaultEngine ; private ScriptScope _defaultScope ; private static IPHelper _helper = new IPHelper(); public static IPHelper Instance { get { return _helper; } } #endregion #region IronPython functions /// /// Get the Default python Engine /// public ScriptEngine DefaultEngine { get { return _defaultEngine; } } /// /// default scrope of default engin /// public ScriptScope DefaultScope { get { return _defaultScope; } } public object Execute(string cmd, ScriptScope scope, ScriptEngine engine) { ScriptSource source = engine.CreateScriptSourceFromString(cmd, Microsoft.Scripting.SourceCodeKind.Statements); return source.Execute(scope); } public object Execute(string cmd, ScriptScope scope) { return this.Execute(cmd, scope, _defaultEngine); } public object Execute(string cmd) { return this.Execute(cmd, _defaultScope, _defaultEngine); } #endregion #region 輸入輸出 public void Print(params object[] objs) { foreach (object o in objs) { Console.Write(o); } } public void PrintLn(params object[] objs) { foreach (object o in objs) { Console.WriteLine(o); } } #endregion }}
執行Run1(), 發現我的目的達到了. 我的.net程式和指令碼實現了最簡單的互動.
下一篇預告:這樣寫很無聊,寫一個簡單的遊戲玩一下...用.net做UI和底層,用指令碼寫邏輯...