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();
}
精彩评论