Host Python In your Application with IronPython2.0.1 (一): 创建交互环境
上一次用了以前下载的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
>>> a
1
>>> b=2
>>> b
2
>>> a==b
False
>>> def hello(name):
... print "hello %s" % name
...
>>> hello('hydonlee')
hello hydonlee
>>> quit
Quit
以后的工作将在2.0.1正式版上进行.不过, 我没有找到api文档?alpha版都有,为什么正式版没有了?

浙公网安备 33010602011771号