2011-01-31 3 views
2

나는 현재 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을 사용하지 않았습니다. 누구든지 도와 줄 수 있습니까?

[편집] 두 질문에 답 : (DESCO의 올바른 방향으로 나를 지적으로 받아 들여) 당신은 파이썬에서 식을 평가하고 그 결과 (1)을 반환하거나 값을 할당 할 수 있습니다

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

일부 변수 범위 이상은 (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

당신은 확실히 그것을 인쇄 할 필요가 없습니다. 나는 이 단지 표현을 평가하는 방법이 될 것을 기대하지만, 그렇지 않은 경우에는 대안이 있다는 것을이 예상합니다. 이 같은 스크립트 범위에서 f을 얻을 다음

def f(x): 
    return x * x 

과 :

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); 
} 
당신은 비슷한 일을 할 수

예를 들어, 내 dynamic graphing demo에 나는 파이썬을 사용하여 함수를 작성 표현식을 여러 번 평가하거나 한 번만 평가하면됩니다.

관련 문제