SourceFileLoader相对导入失败

时间:2019-05-26 07:24:25

标签: python-3.x python-import

当存在相对导入(不是绝对导入)时,importlib的

SourceFileLoader失败。我应该如何指定父模块,以免发生这种情况。例如,

>>> from importlib.machinery import SourceFileLoader                                                                                                                                                    
>>> SourceFileLoader('t_sne', 'venv/lib/python3.5/site-packages/sklearn/manifold/t_sne.py').load_module()                                                                                               

---------------------------------------------------------------------------
SystemError                               Traceback (most recent call last)
<ipython-input-3-553b4ae077de> in <module>
----> 1 SourceFileLoader('t_sne', 'venv/lib/python3.5/site-packages/sklearn/manifold/t_sne.py').load_module()

/usr/lib/python3.5/importlib/_bootstrap_external.py in _check_name_wrapper(self, name, *args, **kwargs)

/usr/lib/python3.5/importlib/_bootstrap_external.py in load_module(self, fullname)

/usr/lib/python3.5/importlib/_bootstrap_external.py in load_module(self, fullname)

/usr/lib/python3.5/importlib/_bootstrap.py in _load_module_shim(self, fullname)

/usr/lib/python3.5/importlib/_bootstrap.py in _load(spec)

/usr/lib/python3.5/importlib/_bootstrap.py in _load_unlocked(spec)

/usr/lib/python3.5/importlib/_bootstrap_external.py in exec_module(self, module)

/usr/lib/python3.5/importlib/_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)

~/PycharmProjects/codemap/venv/lib/python3.5/site-packages/sklearn/manifold/t_sne.py in <module>
     17 from scipy.spatial.distance import squareform
     18 from scipy.sparse import csr_matrix
---> 19 from ..neighbors import NearestNeighbors
     20 from ..base import BaseEstimator
     21 from ..utils import check_array

SystemError: Parent module '' not loaded, cannot perform relative import

首先我还有其他以这种方式加载模块的原因,因此该解决方案应允许我从文件路径加载模块并处理文件中的相对导入。

0 个答案:

没有答案