tags:

views:

35

answers:

2

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 calculator 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;"
} 
+3  A: 

You can do:

var engine = Python.CreateEngine();
dynamic calculator = engine.CreateScope();
engine.Execute(GetPythonScript(), calculator);
Dino Viehland
+2  A: 

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