我目前在做以下操作以创建并执行一个简单的Python计算,采用DLR:IronPython DLR;传递参数给编译的代码?
ScriptRuntime runtime = Python.CreateRuntime();
ScriptEngine engine = runtime.GetEngine("py");
MemoryStream ms = new MemoryStream();
runtime.IO.SetOutput(ms, new StreamWriter(ms));
ScriptSource ss = engine.CreateScriptSourceFromString("print 1+1", SourceCodeKind.InteractiveCode);
CompiledCode cc = ss.Compile();
cc.Execute();
int length = (int)ms.Length;
Byte[] bytes = new Byte[length];
ms.Seek(0, SeekOrigin.Begin);
ms.Read(bytes, 0, (int)ms.Length);
string result = Encoding.GetEncoding("utf-8").GetString(bytes, 0, (int)ms.Length);
Console.WriteLine(result);
它打印“2”到控制台,但是,
我想得到1 + 1的结果而不必打印它(因为这似乎是一个昂贵的操作)。任何我将cc.Execute()的结果赋值为null。有没有其他方法可以从Execute()中得到结果变量?
我也试图找到一种方法来传递参数,即所以结果是arg1 + arg2,不知道该怎么做; Execute的唯一其他重载将ScriptScope作为参数,并且我从未使用过Python。谁能帮忙?
[编辑] 回答两个问题:(德斯科的接受为正确的方向我)
ScriptEngine py = Python.CreateEngine();
ScriptScope pys = py.CreateScope();
ScriptSource src = py.CreateScriptSourceFromString("a+b");
CompiledCode compiled = src.Compile();
pys.SetVariable("a", 1);
pys.SetVariable("b", 1);
var result = compiled.Execute(pys);
Console.WriteLine(result);