我目前正在使用 DLR 执行以下操作来创建和执行简单的 Python 计算:
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() 的结果分配给的任何内容都是空的。有没有其他方法可以从 Execute() 获取结果变量?
我也在尝试找到一种传递参数的方法,即结果是 arg1 + arg2 并且不知道该怎么做; Execute 的唯一其他重载将 ScriptScope 作为参数,我以前从未使用过 python。谁能帮忙?
[编辑] 两个问题的答案:(Desco 接受为我指明了正确的方向)
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);
最佳答案
您可以在 Python 中评估表达式并返回其结果 (1) 或将值赋给作用域中的某个变量,然后再选择它 (2):
var py = Python.CreateEngine();
// 1
var value = py.Execute("1+1");
Console.WriteLine(value);
// 2
var scriptScope = py.CreateScope();
py.Execute("a = 1 + 1", scriptScope);
var value2 = scriptScope.GetVariable("a");
Console.WriteLine(value2);
关于c# - IronPython DLR;将参数传递给编译代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4852386/