2

Situation

Hosted IronPython allows developers to set parameters into script. Every time when a IPy engine object is created, I set such a parameter (ParamName), but when I try to import python module, in which my custom parameter is used, I get an exception with message "global name 'ParamName' is not defined".

Code sample

class PythonScriptingEngine
{
    private ScriptEngine pyEngine;
    private ScriptScope pyScope;

    public PythonScriptingEngine()
    {
        pyEngine = Python.CreateEngine();
        pyScope = pyEngine.CreateScope();
    }

    public object Run(string script)
    {
        ScriptSource source = pyEngine.CreateScriptSourceFromString(script);
        CompiledCode compiled = source.Compile();
        return compiled.Execute(pyScope);
    }

    public void SetParameter(string name, int value)
    {
        pyScope.SetVariable(name, value);
    }
}

// execution
var engine = new PythonScriptingEngine();
engine.SetParameter("ParamName", 10);
engine.Run(@"import SampleScriptWithParamName");

Question

Is there any workaround to this situation? How can I import python script in which custom parameter is used?

CaptainRR
  • 421
  • 5
  • 17
  • Could you provide some source snippets in order to clarifying what you are trying to accomplish? Are you setting a variable on the scope, launching some script text via the scope and importing another module from that script text? – Simon Opelt Dec 14 '12 at 08:12
  • I'm setting a variable on the scope, then I'm trying to import *.py file, which uses this variable. – CaptainRR Dec 14 '12 at 08:20
  • please have a look at Q: http://stackoverflow.com/q/3400525 and A: http://stackoverflow.com/a/3400652/468244 . I think your question is very similar and more python than ironpython related. – Simon Opelt Dec 14 '12 at 08:31
  • I've looked these links, but in my question described another situation. A: http://stackoverflow.com/a/3400652/468244 can't answer my question. – CaptainRR Dec 14 '12 at 08:47
  • If you look at the linked question your SampleScriptWithParamName is equal to file2.py and your engine.Run(@"import SampleScriptWithParamName") is equal to file1.py. Instead of directly defining the variable as foo = "bar", you set it via the hosting environment. The linked answer explains how the scope defined in file1 wont "spill over" to file2 when file2 is imported. That is why your SampleScriptWithParamName won't see the variable. – Simon Opelt Dec 14 '12 at 09:01

1 Answers1

3

As Simon pointed out, the issue is that ParamName is not in scope for SampleScriptWithParamName. One way to achieve that is to add it to the set of builtin variables like so:

public void SetParameter(string name, int value)
{
    pyEngine.GetBuiltinModule().SetVariable(name, value);
}

This should make it available everywhere, but I don't have the ability to test it right now.

Jeff Hardy
  • 7,632
  • 24
  • 24