2010-07-22 5 views
2

Dire que j'ai un script python 'calculator.py':Création d'un objet IronPython (dynamique) à partir d'une chaîne

def Add(x,y) : 
    return x + y; 

je peux instancier un objet dynamique de cette façon:

var runtime = Python.CreateRuntime(); 
dynamic calculator = runtime.UseFile("calculator.py"); 
int result = calculatore.Add(1, 2); 

Existe-t-il un moyen aussi simple d'instancier la calculatrice à partir d'une chaîne en mémoire? Ce que je voudrais obtenir est la suivante:

var runtime = Python.CreateRuntime(); 
string script = GetPythonScript(); 
dynamic calculator = runtime.UseString(script); // this does not exist 
int result = calculatore.Add(1, 2); 

Où pourrait être quelque chose comme GetPythonScript() ceci:

string GetPythonScript() { 
    return "def Add(x,y) : return x + y;" 
} 

Répondre

4

Vous pouvez faire:

var engine = Python.CreateEngine(); 
dynamic calculator = engine.CreateScope(); 
engine.Execute(GetPythonScript(), calculator); 
2

quelque chose comme ça:

public string Evaluate(string scriptResultVariable, string scriptBlock) 
{ 
    object result; 

    try 
    { 
     ScriptSource source = 
      _engine.CreateScriptSourceFromString(scriptBlock, SourceCodeKind.Statements); 

     result = source.Execute(_scope); 
    } 
    catch (Exception ex) 
    { 
     result = "Error executing code: " + ex; 
    } 

    return result == null ? "<null>" : result.ToString(); 
} 
Questions connexes