2014-10-17 74 views
2

我試圖使用託管在.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版本,其中一些方法和簽名已更改。

+0

東西你把到'ScriptRuntime.Globals'範圍必須進口。這與聲明一個可在任何範圍內訪問的全局變量不同,至少不在IronPython中。 – 2014-10-18 05:27:50

回答

5

這裏是我會提供一個可變的劇本,後來挑結果的方式:

 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")); 
0

要添加到Pawal的回答,以這種方式設置的變量是不是「全球性」,不能通過導入的函數訪問。我從here瞭解到,這是如何讓他們通過全球所有的和可訪問:

var engine = Python.CreateEngine(); 
engine.GetBuiltinModule().SetVariable("foo", 42); 
相關問題