My question is similar to How to import a module with a full path? However, I do not import the source .py file, I import the package with .pyd.
At run time, I create new package modules from some dynamically generated code. I successfully generated a Foo package with a file __init__.pyand mod.pyd:
/a/temp/dir/foo/
__init__.py
bar.pyd
Sample code I'm working with
import importlib.util
spec = importlib.util.spec_from_file_location("foo.bar", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.bar()
If I try to use spec_from_file_location('foo.bar', '/a/temp/dir/foo/__init__.py'), the module barfrom pyd does not load.
If I try to use spec_from_file_location('foo.bar', '/a/temp/dir/foo/'), it spec_from_file_locationreturns None.
If I try to use spec_from_file_location('foo.bar', '/a/temp/dir/foo/bar.pyd'), I get the following error stack:
File "<frozen importlib._bootstrap>", line 577, in module_from_spec
File "<frozen importlib._bootstrap_external>", line 903, in create_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed.
4- importlib MetaPathFinder SourceLoader. MetaPathFinder , , Loader. get_data Unicode- python. pyd ?
class MyLoader(importlib.abc.SourceLoader):
def __init__(self, fullname, path, pyd):
self.path = path
self.fullname = fullname
self.pyd = pyd
def get_data(self, path):
print('*** get_data', path)
with open(os.path.join(self.path, self.pyd), 'r') as f:
return f.read()
def get_filename(self, fullname):
print('*** get_filename', fullname)
return os.path.join(self.path, '__init__.py')
def is_package(self):
return True
class MyFinder(MetaPathFinder):
def __init__(self, this_module, workdir, pyd):
self._this_module = this_module
self._workdir = workdir
self._pyd = pyd
def find_spec(self, fullname, path, target=None):
print('find_spec', fullname, path, target, self._this_module)
if fullname != self._this_module:
return
filename = os.path.join(self._workdir, self._this_module)
spec = ModuleSpec(
name = fullname,
loader = MyLoader(fullname, filename, self._pyd),
origin = filename,
loader_state = 1234,
is_package = True,
)
return spec
def is_package(self):
return True