当我尝试添加对IronPython引擎实例的引用时,引用get将按预期添加到引用中。如果我创建引擎的另一个实例,则AddReference执行时没有错误,但引用未添加到引用,并且import语句失败,并且“没有名为...的模块”。
var engine = Python.CreateEngine();
dynamic clr = engine.Runtime.GetClrModule();
clr.AddReference("IronPython.StdLib");
var references = (IEnumerable<Assembly>)clr.References;
Debug.Assert(references.Any(asm => asm.FullName.StartsWith("IronPython.StdLib"))); // ok
var source = "import pydoc\npydoc.plain(pydoc.render_doc(str))";
var result = engine.Execute<string>(source);
Debug.Assert(result.StartsWith("Python Library Documentation")); // ok
var engine2 = Python.CreateEngine();
dynamic clr2 = engine2.Runtime.GetClrModule();
clr2.AddReference("IronPython.StdLib");
var references2 = (IEnumerable<Assembly>)clr.References;
Debug.Assert(references2.Any(asm => asm.FullName.StartsWith("IronPython.StdLib"))); // fails
result = engine.Execute<string>(source); // throws ImportException "no module named pydoc"
Debug.Assert(result.StartsWith("Python Library Documentation"));
我尝试使用IronPython 2.7.5的二进制版本(安装到GAC)和C#4.5,IronPython.StdLib
是使用pyc的Python标准库的预编译DLL。
我也尝试过使用github自编译的IronPython 2.7.5和2.7.6,但是第一个engine.execute
已经失败了,"no module named pydoc"
虽然添加了引用。
我做错了什么或者只是一个错误?
答案 0 :(得分:0)
一位同事发现了失败的原因。我在这里发布,以防其他人偶然发现这个问题。
添加引用后需要加载程序集:
var engine = Python.CreateEngine();
dynamic clr = engine.Runtime.GetClrModule();
clr.AddReference("IronPython.StdLib");
// load assembly into engine
var assembly = Assembly.LoadFrom("IronPython.StdLib.dll");
engine.Runtime.LoadAssembly(assembly);
var references = (IEnumerable<Assembly>)clr.References;
Debug.Assert(references.Any(asm => asm.FullName.StartsWith("IronPython.StdLib"))); // ok
var source = "import pydoc\npydoc.plain(pydoc.render_doc(str))";
var result = engine.Execute<string>(source);
Debug.Assert(result.StartsWith("Python Library Documentation")); // ok
var engine2 = Python.CreateEngine();
dynamic clr2 = engine2.Runtime.GetClrModule();
clr2.AddReference("IronPython.StdLib");
// load assembly into engine2
engine2.Runtime.LoadAssembly(assembly);
var references2 = (IEnumerable<Assembly>)clr.References;
Debug.Assert(references2.Any(asm => asm.FullName.StartsWith("IronPython.StdLib"))); // does not fail
result = engine.Execute<string>(source); // does not throw any more
Debug.Assert(result.StartsWith("Python Library Documentation"));