【问题标题】:Why does clr.AddReference fail on second IronPython engine?为什么 clr.AddReference 在第二个 IronPython 引擎上失败?
【发布时间】:2016-08-22 11:56:19
【问题描述】:

当我尝试添加对 IronPython 引擎实例的引用时,引用 get 已按预期添加到引用中。如果我创建引擎的另一个实例,AddReference 执行时不会出现错误,但引用不会添加到引用中,并且导入语句会失败并显示“没有名为 ...”的模块。

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" 尽管添加了引用。

我做错了什么还是只是一个错误?

【问题讨论】:

    标签: c# .net scripting ironpython


    【解决方案1】:

    一位同事找出了失败的原因。我把它贴在这里,以防其他人偶然发现这个问题。

    添加引用后需要加载程序集:

    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"));
    

    【讨论】:

      猜你喜欢
      • 2019-09-07
      • 1970-01-01
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 2020-01-19
      相关资源
      最近更新 更多