Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting and getting variables in .Net hosted IronPython script

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.

like image 708
Crab Bucket Avatar asked Oct 17 '14 14:10

Crab Bucket


1 Answers

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"));
like image 167
Pawel Jasinski Avatar answered Nov 15 '22 03:11

Pawel Jasinski