2011-01-31 61 views
2

我目前在做以下操作以創建並執行一個簡單的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); 

回答

6

您可以在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); 
3

你絕對不必打印它。我想預計那裏有一種方式來評估一個表達式,但如果沒有其他選擇。

例如,在我的dynamic graphing demo我創建一個函數,使用Python:

def f(x): 
    return x * x 

,然後得到f了腳本的範圍是這樣的:

Func<double, double> function; 
if (!scope.TryGetVariable<Func<double, double>>("f", out function)) 
{ 
    // Error handling here 
} 
double step = (maxInputX - minInputX)/100; 
for (int i = 0; i < 101; i++) 
{ 
    values[i] = function(minInputX + step * i); 
} 

你可以做同樣的事情如果您想多次評估表達式,或者只是將結果分配給變量,如果您只需要評估一次。