IronPython在托管时如何加载模块?

时间:2017-06-08 16:55:05

标签: python .net ironpython

我对IronPython在托管时加载模块的方式感到困惑。

我使用的是使用MSI软件包安装的IronPython 2.7.7,我引用了C:\Program Files (x86)\IronPython 2.7\IronPython.dllC:\Program Files (x86)\IronPython 2.7\Microsoft.Scripting.dll

有时IronPython无法加载抛出IronPython.Runtime.Exceptions.ImportException: 'No module named modulename'的模块,但有时候一切正常。

例如,

var engine = Python.CreateEngine();
engine.CreateScriptSourceFromString("import datetime; print datetime.datetime.now()").Execute();

有效,但

var engine = Python.CreateEngine();
engine.CreateScriptSourceFromString("import json; print json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])").Execute();

我发现了在engine中设置搜索路径的建议。所以我添加了

var searchPaths = engine.GetSearchPaths();
searchPaths.Add(@"C:\Program Files (x86)\IronPython 2.7\Lib");
engine.SetSearchPaths(searchPaths);

现在使用json模块的示例正常工作。

但我从engine获得的搜索路径仅包含

  1. "."
  2. "D:\\IronPythonTest\\bin\\Debug\\Lib"
  3. "D:\\IronPythonTest\\bin\\Debug\\DLLs"
  4. 我的Lib文件夹下没有DLLsDebug个文件夹。

    那么IronPython如何设法加载datetime模块?

    提前感谢您的澄清。

1 个答案:

答案 0 :(得分:3)

将相关路径添加到引擎的基本方法是正确的。

IronPython使用大量标准库(尽可能使用)。在CPython中本地实现的低级模块在C#for IronPython中实现。其中一个modulesdatetime。因此,只要有IronPython.Modules.dll,即使没有特定的加载/路径处理,也可以使用几个标准模块。