IronPython ResourceMetaPathImporter failure
本文关键字:failure ResourceMetaPathImporter IronPython | 更新日期: 2023-09-27 18:33:59
许多使用 ResourceMetaPathImporter 的解决方案如下所示:
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();
特别是,这段代码模仿了这个答案:IronPython 依赖项存储为字符串的脚本。但是我使用的是 IronPython 2.7.5,上面的代码片段总是抱怨没有 csv 模块。
谁能告诉我问题?2.7.5 以某种方式损坏了吗?我觉得我错过了一些明显的东西。
您的问题与 IronPython 2.7.5 无关,而是与您的运行时设置或压缩库有关。您的代码段没有显示提供了哪些选项,但该区域似乎出了问题。如果提供空选项或选项不足import csv
将失败。
如果删除脚本运行时设置(前三行)并仅使用Python.CreateEngine()
中创建的引擎而不是engineInstance
则事情应该按预期工作。
完整的代码段看起来像
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();
正如问题作者所述 - 压缩库存档中的错误文件夹结构也会使导入出错。