问题
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
"."
"D:\\IronPythonTest\\bin\\Debug\\Lib"
"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