说我有一个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;"
}
答案 0 :(得分:4)
你可以这样做:
var engine = Python.CreateEngine();
dynamic calculator = engine.CreateScope();
engine.Execute(GetPythonScript(), calculator);
答案 1 :(得分:2)
做这样的事情:
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();
}