How does IronPython loads modules while being hosted?

丶灬走出姿态 提交于 2019-12-24 03:07:07

问题


I'm confused about the way IronPython loads modules while being hosted.

I'm using IronPython 2.7.7 installed using the MSI package and I've referenced C:\Program Files (x86)\IronPython 2.7\IronPython.dll and C:\Program Files (x86)\IronPython 2.7\Microsoft.Scripting.dll.

Sometimes IronPython fails to load a module throwing IronPython.Runtime.Exceptions.ImportException: 'No module named modulename', but sometimes everything works fine.

For example,

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

works, but

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

doesn't.

I've found a suggestion to set search paths in engine. So I've added

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

and now the example which uses json module works.

But search paths which I get from engine contain only

  1. "."
  2. "D:\\IronPythonTest\\bin\\Debug\\Lib"
  3. "D:\\IronPythonTest\\bin\\Debug\\DLLs"

And I don't have neither Lib nor DLLs folders under my Debug folder.

So how does IronPython manage to load datetime module?

Thanks in advance for the clarification.


回答1:


Your basic approach in adding the relevant paths to the engine is correct.

IronPython uses large amounts of the standard library (wherever possible). Low level modules that are implemented natively in CPython are implemented in C# for IronPython. One of those modules is datetime. So as long as IronPython.Modules.dll is around, several standard modules are available even without specific loading/path handling.



来源:https://stackoverflow.com/questions/44441574/how-does-ironpython-loads-modules-while-being-hosted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!