开发者

Creating an IronPython (dynamic) object from a string

开发者 https://www.devze.com 2023-01-08 06:30 出处:网络
Say I have a python script \'calculator.py\': def Add(x,y) : return x + y; I can instantiate a dynamic object from this like so:

Say I have a python script 'calculator.py':

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

I can instantiate a dynamic object from this like so:

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

Is there a similarly easy way to instantiate the calculato开发者_如何学Cr from an in-memory string? What I would like to obtain is this:

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

Where GetPythonScript() could be something like this:

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


You can do:

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


Do something like this:

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

精彩评论

暂无评论...
验证码 换一张
取 消