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;"
} 

2 Answers 2

4

You can do:

var engine = Python.CreateEngine();
dynamic calculator = engine.CreateScope();
engine.Execute(GetPythonScript(), calculator);
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.