Setting and getting variables in .Net hosted IronPython script

丶灬走出姿态 提交于 2019-12-21 19:41:39

问题


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

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

I am a complete newbie with IronPython so apologies if this is an easy/obvious question.

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.


回答1:


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



回答2:


To add onto Pawal's answer, the variables set in this manner are not "global" and can't be accessed by imported functions. I learned from here, that this is how to make them global and accessible by all:

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


来源:https://stackoverflow.com/questions/26426955/setting-and-getting-variables-in-net-hosted-ironpython-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!