在python3中导入本地共享库

2024-04-25 23:50:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在我的swig文件夹中的lib/文件夹中构建了我的库,因为我需要共享库(.so)在包中,而不需要在安装时构建它。 没有对swig_import_helper进行任何修改,我就得到了错误

Traceback (most recent call last):
  File "/MyProject/swig_wrapper.py", line 6, in <module>
    import swig_decoders
  File "/MyProject/swig/swig_decoders.py", line 26, in <module>
    _swig_decoders = swig_import_helper()
  File "/MyProject/swig/swig_decoders.py", line 25, in swig_import_helper
    return importlib.import_module('_swig_decoders')
  File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named '_swig_decoders'

因此,我修改了importlib,以便加载本地库:

def swig_import_helper():
        import importlib
        pkg = __name__.rpartition('.')[0]
        mname = '.'.join((pkg, '_swig_decoders')).lstrip('.')
        try:
            return importlib.import_module(mname)
        except ImportError:
            try:
                import os
                import importlib.util
                BASE_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)))
                spec = importlib.util.spec_from_file_location("module._swig_decoders", os.path.join(BASE_PATH, 'lib'))
                foo = importlib.util.module_from_spec(spec)
                spec.loader.exec_module(foo)
            except:
                return importlib.import_module('_swig_decoders')
    _swig_decoders = swig_import_helper()

这些库位于本地路径swig/lib

MyProject/swig/lib/swig_decoders-1.1-py3.7-linux-x86_64.egg/
EGG-INFO                    _swig_decoders.cpython-37m-x86_64-linux-gnu.so  swig_decoders.py
__pycache__                 _swig_decoders.py

但我现在仍然收到一个导入错误:

  File "MyProject/swig/swig_decoders.py", line 14, in swig_import_helper
    return importlib.import_module(mname)
  File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named '_swig_decoders'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "MyProject/swig/swig_decoders.py", line 21, in swig_import_helper
    foo = importlib.util.module_from_spec(spec)
  File "<frozen importlib._bootstrap>", line 580, in module_from_spec
AttributeError: 'NoneType' object has no attribute 'loader'

这是由于库路径错误还是由于使用importlib.util.spec_from_file_location时的importlib造成的

strong文本


Tags: inpyimporthelperreturnlibmyprojectline

热门问题