上一次用了以前下載的IronPython 2.0 A1版, 今天下載了正式版2.0.1,發現變化不小啊...我過時了.
原有的代碼已經不能正常運行, 於是在2.0.1正式版上再調整了一下.
using System;using System.Collections.Generic;using System.Text;using IronPython.Hosting;using IronPython.Runtime;using Microsoft.Scripting;using Microsoft.Scripting.Hosting;namespace IPConsole { class Program { static void Main(string[] args) { /* * 方法一: 通過ScriptRuntimeSetup讀取設定檔,載入動態語言引擎 ScriptRuntimeSetup srs = ScriptRuntimeSetup.ReadConfiguration(); ScriptRuntime runtime = new ScriptRuntime(srs); ScriptEngine engine = runtime.GetEngine("Python"); *****/ /* * 方法二:通過ScriptRuntime讀取設定檔,載入引擎 ScriptRuntime runtime = ScriptRuntime.CreateFromConfiguration(); ScriptEngine engine = runtime.GetEngine("Python"); * ***/ /* * 方法三:直接建立引擎 * ***/ ScriptEngine engine = Python.CreateEngine(); StringBuilder cmdBuff = new StringBuilder(); string line = ""; Console.WriteLine(string.Format("IronPython {0} ", engine.LanguageVersion)); //print version ScriptScope scope = engine.CreateScope(); //進入互動 while (true) { if (cmdBuff.Length == 0) { Console.Write(">>> "); //first prompt } else { Console.Write("... "); //2nd and above prompt } //get command line line = Console.ReadLine(); cmdBuff.AppendLine(line); if (line.StartsWith(" ") | line.StartsWith("\t") | line.EndsWith(":")){ //do nothing...get next input } else { //get the command and execute it string cmd = cmdBuff.ToString(); try { if (cmd.TrimEnd() == "quit") break; //需要建立ScriptSource執行,InteractiveCode為互動環境 ScriptSource source = engine.CreateScriptSourceFromString(cmd, SourceCodeKind.InteractiveCode); source.Execute(scope); } catch (Exception e) { Console.WriteLine(e.Message); } //clear command buffer cmdBuff.Length = 0; } } Console.WriteLine("Quit"); } }}
在這裡,建立引擎共有三種方式,其中前兩種需要設定檔app.config配合, 如下:
<?xml version="1.0" encoding="utf-8" ?><configuration> <configSections> <section name="microsoft.scripting" type="Microsoft.Scripting.Hosting.Configuration.Section, Microsoft.Scripting" requirePermission="false" /> </configSections> <microsoft.scripting> <languages> <language names="IronPython,Python,py" extensions=".py" displayName="IronPython 2.0.1" type="IronPython.Runtime.PythonContext,IronPython" /> <!-- 可以添加其它引擎, 如IronRuby --> </languages> </microsoft.scripting></configuration>
再看一下測試結果吧, 比原來好了. 因為這個互動模式: 輸入a也會顯示a的值了,而不一定非要print
IronPython 2.0.0.0>>> a=1>>> a1>>> b=2>>> b2>>> a==bFalse>>> def hello(name):... print "hello %s" % name...>>> hello('hydonlee')hello hydonlee>>> quitQuit
以後的工作將在2.0.1正式版上進行.不過, 我沒有找到api文檔?alpha版都有,為什麼正式版沒有了?