Setting and getting variables in .Net hosted IronPython script
Asked Answered
T

2

5

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.

Tenth answered 17/10, 2014 at 14:11 Comment(1)
Stuff you put in to the ScriptRuntime.Globals scope must be imported. It's not the same as declaring a global variable accessible in any scope, at least, not in IronPython.Clio
J
9

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"));
Jeddy answered 19/10, 2014 at 16:37 Comment(0)
H
3

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);
Hudgins answered 17/8, 2017 at 11:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.