【问题标题】:Setting and getting variables in .Net hosted IronPython script在 .Net 托管 IronPython 脚本中设置和获取变量
【发布时间】:2014-10-17 14:11:58
【问题描述】:

我正在尝试使用托管在 .Net 控制台应用程序中的 IronPython 对验证规则引擎进行原型设计。我已将脚本精简到我认为是基础的内容

var engine = Python.CreateEngine();
engine.Execute("from System import *");
engine.Runtime.Globals.SetVariable("property_value", "TB Test");
engine.Runtime.Globals.SetVariable("result", true);

var sourceScope = engine.CreateScriptSourceFromString("result = property_value != None and len(property_value) >= 3");
sourceScope.Execute();

bool result = engine.Runtime.Globals.GetVariable("result");

engine.Runtime.Shutdown();

但它无法检测到我认为我已经设置的全局变量。使用

执行脚本时失败
global name 'property_value' is not defined

但我可以检查作用域中的全局变量并且它们在那里 - 当我在调试器中运行时,此语句返回 true

sourceScope.Engine.Runtime.Globals.ContainsVariable("property_value")

我是 IronPython 的新手,如果这是一个简单/明显的问题,我深表歉意。

这样做的一般动机是创建this kind of rules engine,但使用更高(最新)版本的 IronPython,其中一些方法和签名发生了变化。

【问题讨论】:

  • 必须导入您放入 ScriptRuntime.Globals 范围的内容。这与声明一个可在任何范围内访问的全局变量不同,至少在 IronPython 中不能。

标签: .net ironpython


【解决方案1】:

这是我为脚本提供变量并随后选择结果的方式:

        var engine = Python.CreateEngine();
        var scope = engine.CreateScope();
        scope.SetVariable("foo", 42);
        engine.Execute("print foo; bar=foo+11", scope);
        Console.WriteLine(scope.GetVariable("bar"));

【讨论】:

    【解决方案2】:

    为了补充 Pawal 的答案,以这种方式设置的变量不是“全局”的,并且不能被导入的函数访问。我从here 那里了解到,这是使它们全球化并可供所有人访问的方法:

    var engine = Python.CreateEngine();
    engine.GetBuiltinModule().SetVariable("foo", 42);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-16
      • 2022-09-27
      相关资源
      最近更新 更多