IronPython 的表达式树
我使用此代码通过 IronPython 执行 python 表达式。
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
scope.SetVariable("m", mobject);
string code = "m.ID > 5 and m.ID < 10";
ScriptSource source =
engine.CreateScriptSourceFromString(code, SourceCodeKind.Expression);
source.Execute(scope);
有没有办法将生成的表达式树作为 c# 对象,例如 BlockExpression ?
I use this code to execute a python expression using IronPython.
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
scope.SetVariable("m", mobject);
string code = "m.ID > 5 and m.ID < 10";
ScriptSource source =
engine.CreateScriptSourceFromString(code, SourceCodeKind.Expression);
source.Execute(scope);
Is there a way to get the produced Expression Tree as c# object, e.g. the BlockExpression
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
IronPython 的内部 AST 也恰好是表达式树,因此您只需要获取代码的 AST,您可以使用
IronPython.Compiler.Parser
类。 Parser.ParseFile 方法将返回 < code>IronPython.Compiler.Ast.PythonAst 表示代码的实例。使用解析器有点棘手,但您可以查看 _ast 模块的
BuildAst
方法 以获得一些提示。基本上,它是:ThrowingErrorSink
也来自_ast
模块。您可以像这样获取SourceUnit
实例(参见compile
builtin):然后你必须遍历 AST 才能从中获取有用的信息,但它们应该是相似的(但不是与)C# 表达式树相同。
IronPython's internal ASTs also happen to be Expression trees, so you just need to get the AST for your code, which you can do using the
IronPython.Compiler.Parser
class. The Parser.ParseFile method will return aIronPython.Compiler.Ast.PythonAst
instance representing the code.Using the parser is a bit tricky, but you can look at the
BuildAst
method of the _ast module for some hints. Basically, it's:ThrowingErrorSink
also comes from the_ast
module. You can get aSourceUnit
instance like so (c.f.compile
builtin):You then have to walk the AST to get useful information out of it, but they should be similar (but not identical to) C# expression trees.