Создание IronPython (динамического) объекта из строки - PullRequest
2 голосов
/ 23 июля 2010

Скажем, у меня есть скрипт на python 'calculator.py':

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

Я могу создать из этого динамический объект, например, так:

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

Есть ли такой же простой способсоздать калькулятор из строки в памяти?Я хотел бы получить следующее:

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

Где GetPythonScript () может выглядеть примерно так:

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

Ответы [ 2 ]

4 голосов
/ 23 июля 2010

Вы можете сделать:

var engine = Python.CreateEngine();
dynamic calculator = engine.CreateScope();
engine.Execute(GetPythonScript(), calculator);
2 голосов
/ 23 июля 2010

Сделайте что-то вроде этого:

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();
}
...