我試圖使用託管在.Net控制檯應用程序中的IronPython驗證規則引擎的原型。我已將文字剝離到我認爲是基礎的東西在.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
執行,但我可以檢查範圍的全局變量和他們在那裏失敗 - 當我在調試器中運行這個語句返回真
sourceScope.Engine.Runtime.Globals.ContainsVariable("property_value")
我如果這是一個簡單/明顯的問題,那麼IronPython的一個完整的新手會非常抱歉。
對此的一般動機是創建this kind of rules engine,但帶有後來(最新版本)的IronPython版本,其中一些方法和簽名已更改。
東西你把到'ScriptRuntime.Globals'範圍必須進口。這與聲明一個可在任何範圍內訪問的全局變量不同,至少不在IronPython中。 – 2014-10-18 05:27:50