Is there a way to catch some kind of even from IronPython when it attempts to resolve/load a module that it cannot find?
We want to store modules in a database or embed them in a DLL and import them by calling import mymodule
. We don't want to involve the filesystem at all. When we say import something
, we do not want it looking in \Lib or any filesystem.
The following code works fine for loading a chunk of Python embedded in a DLL. It works only when there are no imports.
var myScript = new StreamReader(Assembly.GetAssembly(this.GetType()).GetManifestResourceStream("Resource.Name.To.My.Script")).ReadToEnd()
var engine = IronPython.Hosting.Python.CreateEngine();
var scope = engine.CreateScope();
var result = engine.Execute(myScript, scope);
And the python code:
print('hello world')
If there is an import, things do not work. It doesn't know how to resolve the location of the module.
The only way I can make it work is by making sure that any modules that we need are visible to the engine from the filesystem. This involves using engine.GetSearchPaths() (to see what paths it is looking for) and using engine.SetSearchPaths() to append any additional search paths. But these are from the file system and that is not what I want.
I imagine a nice way might be to receive some kind of an event from the engine like "OnLookingForModuleNamedXYZ(moduleName)". And then I can look up the module in the database or in the DLL's embedded resources and send back the string for the module.
How can I do this?