使用.net执行python代码,解析表达式

以前听说过.net可以执行python代码,这次终于派上用场了
NUGET 安装 IronPython .NET版本4.8以下选择 2.7.8 这个版本

public static string ExecPython(string pyCode)
{
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
var sourceCode = engine.CreateScriptSourceFromString(pyCode);
var result = sourceCode.Execute<object>(scope);
return result.ToString();
}

关键词需要符合python的语法规范

对于简单表达式,自带的DataTable也能解析,测试无法判断 ==
但是速度比py的快

string expression = "1+1";
DataTable eval = new DataTable();
object result = eval.Compute(expression, "");
Console.WriteLine(result);

2020.11 Update

转成js去执行也挺好,费这个劲搞python划不来
引用 Microsoft.JScript
注意判断= =用 = = =

static VsaEngine Engine = VsaEngine.CreateEngine();
static string EvalJScript(string JScript)
{
string Result = null;
try
{
Result = Microsoft.JScript.Eval.JScriptEvaluate(JScript, Engine).ToString();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return Result;
}

不过上面那个效率实在是实在是非常低,换下面这个

public class JsEngine
{
public static int EvalToInteger(string statement)
{
string s = EvalToString(statement);
return int.Parse(s.ToString());
}
public static double EvalToDouble(string statement)
{
string s = EvalToString(statement);
return double.Parse(s);
}
public static string EvalToString(string statement)
{
object o = EvalToObject(statement);
return o.ToString();
}
public static object EvalToObject(string statement)
{
return _evaluatorType.InvokeMember(
"Eval",
BindingFlags.InvokeMethod,
null,
_evaluator,
new object[] { statement }
);
}
static JsEngine()
{
ICodeCompiler compiler;
compiler = new JScriptCodeProvider().CreateCompiler();
CompilerParameters parameters;
parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
CompilerResults results;
results = compiler.CompileAssemblyFromSource(parameters, _jscriptSource);
Assembly assembly = results.CompiledAssembly;
_evaluatorType = assembly.GetType("Evaluator.Evaluator");
_evaluator = Activator.CreateInstance(_evaluatorType);
}
private static object _evaluator = null;
private static Type _evaluatorType = null;
private static readonly string _jscriptSource =
@"package Evaluator
{
class Evaluator
{
public function Eval(expr : String) : String
{
return eval(expr);
}
}
}";
}
posted @   trykle  阅读(444)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示