在.Net托管的IronPython脚本中设置和获取变量 [英] Setting and getting variables in .Net hosted IronPython script
问题描述
我正在尝试使用.Net控制台应用程序中托管的IronPython制作验证规则引擎的原型.我已经将脚本剥离为我认为是最基础的
I'm trying to prototype a validation rules engine using IronPython hosted in a .Net console application. I've stripped the script right down to what I believe is the basics
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();
但是它无法检测到我认为已设置的全局变量.使用
It can't however detect the global variables that I think I have set up. It fails when the script is executed with
global name 'property_value' is not defined
但是我可以检查范围内的全局变量,它们在那里-当我在调试器中运行时,此语句返回true
but i can check the global variables in the scope and they are there - this statement returns true when I run in in the debugger
sourceScope.Engine.Runtime.Globals.ContainsVariable("property_value")
我是IronPython的一个完全新手,如果这是一个简单/明显的问题,我深表歉意.
I am a complete newbie with IronPython so apologies if this is an easy/obvious question.
通常这样做的动机是创建这种规则引擎,但是在IronPython的更高版本(最新)中,某些方法和签名已更改.
The general motivation to this is creating this kind of rules engine but with a later (most recent) version of IronPython where some of the methods and signatures have changed.
推荐答案
以下是我向脚本提供变量并随后选择结果的方法:
Here is the way I would provide script with a variable and pick the results afterwards:
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"));
这篇关于在.Net托管的IronPython脚本中设置和获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!