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.

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. Commented Oct 18, 2014 at 5:27

2 Answers 2

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"));
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.