【问题标题】:Expression tree from IronPythonIronPython 的表达式树
【发布时间】:2011-05-23 12:36:49
【问题描述】:

我使用这段代码使用 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 ?

【问题讨论】:

  • 你在哪里传递代码?
  • 我参考了 Microsoft Scripting 库和 IronPython。我正在使用 .net 4.0

标签: linq ironpython expression-trees


【解决方案1】:

IronPython 的内部 AST 也恰好是表达式树,因此您只需为您的代码获取 AST,您可以使用 IronPython.Compiler.Parser 类来完成。 Parser.ParseFile 方法将返回一个代表代码的IronPython.Compiler.Ast.PythonAst 实例。

使用解析器有点棘手,但您可以查看 _ast 模块的BuildAst method 以获得一些提示。基本上是:

Parser parser = Parser.CreateParser(
    new CompilerContext(sourceUnit, opts, ThrowingErrorSink.Default),
    (PythonOptions)context.LanguageContext.Options);

PythonAst ast = parser.ParseFile(true);

ThrowingErrorSink 也来自_ast 模块。您可以像这样获得SourceUnit 实例(c.f. compile builtin):

SourceUnit sourceUnit = context.LanguageContext.CreateSnippet(source, filename, SourceCodeKind.Statements);

然后您必须遍历 AST 以从中获取有用的信息,但它们应该类似于(但不等同于)C# 表达式树。

【讨论】:

  • 这里的context 是什么?
  • @Asad:一个 CodeContext 实例。我相信您也可以从 ScriptEngine 中获取 LanguageContext 实例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-11
  • 2011-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多