Embedding IronPython 2 in C # - What is the replacement for DefaultModule.Globals?

I am trying to convert IronPython 1 code:

var ptype = this.engine.DefaultModule.Globals[ironPythonClassName];

      

I have a script that declares a class. I am using Python engine to execute script.

How do I get variable names (including class) in IronPython 2?

+2


source to share


2 answers


There is no need to create a new scope as the CompiledCode instance is created with one.

ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromFile(fileName);
CompiledCode code = source.Compile();
ScriptScope scope = code.DefaultScope;
code.Execute();
var names = scope.GetVariableNames();

      


rant on

The scripts above are a bit of a nightmare - there is too much duplication of functionality and strange communication between instances.



Why didn't MS use the well-known "engine execute code compiled from source in scope"?

So the model can be:

  • compile source to generate code (compiler class)
  • provide or create a scope (scope class)
  • bind the code and scope and pass them to the executable engine (engine class)

rant off

+1


source


You have to execute the file in scope:

ScriptScope scope = engine.CreateScope();
CompiledCode code = engine.CreateScriptSourceFromFile(fullPath).Compile();
code.Execute(scope);

      

From the scope, you can call GetVariable or GetVariable to get the value of a variable:

object c = scope.GetVariable(ironPythonClassName)
// or
int i = scope.GetVariable<int>(otherVar);

      



As far as I know, the DefaultModule is completely gone in IronPython 2.x.

For simplicity, there are also ScriptEngine convenience methods:

ScriptScope scope = engine.ExecuteFile(fullPath);
names = scope.GetVariableNames()

      

It's easier for a one-time use script, but using the compiled code directly is better (faster) if you re-execute the same script.

+1


source







All Articles