2

Many solutions for using ResourceMetaPathImporter look like the following:

ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(options);
var pyRuntime = new ScriptRuntime(setup);
var engineInstance = Python.GetEngine(pyRuntime);

var engine = Python.CreateEngine();
var sysScope = engine.GetSysModule();
List metaPath = sysScope.GetVariable("meta_path");
var importer = new ResourceMetaPathImporter(typeof(EmbeddedPythonEngine).Assembly, "python_27_lib.zip");
metaPath.Add(importer);
sysScope.SetVariable("meta_path", metaPath);

var source = "import csv";
var script = engineInstance.CreateScriptSourceFromString(source, SourceCodeKind.Statements);
script.Execute();

In particular, this code mimicks this answer: IronPython dependencies for scripts stored as strings. However I am using IronPython 2.7.5 and the above snippet always complains that there is no csv module.

Can anyone let me know the problem? Is 2.7.5 broken somehow? I feel like I missed something obvious.

Community
  • 1
  • 1
Simon P
  • 1,196
  • 1
  • 12
  • 26

1 Answers1

2

Your problems are not related to IronPython 2.7.5 but your runtime setup or compressed library. Your snippet does not show what options are provided but things seem to go wrong in that area. If empty or insufficient options are provided import csv will fail.

If you remove the script runtime setup (first three lines) and just use the engine created in Python.CreateEngine() instead of engineInstance things should work as expected.

The full snippet would look like

var engine = Python.CreateEngine();
var sysScope = engine.GetSysModule();
List metaPath = sysScope.GetVariable("meta_path");
var importer = new ResourceMetaPathImporter(typeof(EmbeddedPythonEngine).Assembly, "python_27_lib.zip");
metaPath.Add(importer);
sysScope.SetVariable("meta_path", metaPath);

var source = "import csv";
var script = engine.CreateScriptSourceFromString(source, SourceCodeKind.Statements);
script.Execute();

As stated by the author of the question - a wrong folder structure within the compressed library archive also faults the import.

Simon Opelt
  • 6,136
  • 2
  • 35
  • 66
  • Turns out that my python_27_lib.dll should _not_ have the Lib/ folder in the structure and then it works... however, thanks for the clarifications! (the setup was hidden as I also have my own script host to intercept module loading too using the PlatformAdaptionLayer). – Simon P Feb 11 '16 at 17:43