KeyError / frozen importlib._bootstrap 在 spyder 中导入第二个库时出错

KeyError / frozen importlib._bootstrap error on second library import in spyder

我收到了

File " <frozen importlib._bootstrap_external> ", line 978, in _get_parent_path    
KeyError: 'python_library'

当我在 spyder 中第二次从子文件夹导入库时出错,但第一次(在重新启动 spyder 之后)或在 spyder 之外它工作正常。

密码是:

from python_library.tools.test_lib import test_func    
test_func()

其中 test_lib.py 就是

def test_func():    
    print('Hello!')

输出为:

runfile('/home/user/Desktop/test.py', wdir='/home/user/Desktop')
Hello!

runfile('/home/user/Desktop/test.py', wdir='/home/user/Desktop')    
Reloaded modules: python_library, python_library.tools.test_lib
Traceback (most recent call last):

  File "< ipython-input-2-e750fd08988c >", line 1, in <module>   
    runfile('/home/user/Desktop/test.py', wdir='/home/user/Desktop')

  File "/home/user/anaconda3/envs/qutip/lib/python3.6/site-packages/spyder_kernels/customize/spydercustomize.py", line 678, in runfile    
    execfile(filename, namespace)

  File "/home/user/anaconda3/envs/qutip/lib/python3.6/site-packages/spyder_kernels/customize/spydercustomize.py", line 106, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/home/user/Desktop/test.py", line 1, in <module>
    from python_library.tools.test_lib import test_func

  File "<frozen importlib._bootstrap>", line 971, in _find_and_load

  File "<frozen importlib._bootstrap>", line 951, in _find_and_load_unlocked

  File "<frozen importlib._bootstrap>", line 894, in _find_spec

  File "<frozen importlib._bootstrap_external>", line 1157, in find_spec

  File "<frozen importlib._bootstrap_external>", line 1123, in _get_spec

  File "<frozen importlib._bootstrap_external>", line 994, in __iter__

  File "<frozen importlib._bootstrap_external>", line 982, in _recalculate

  File "<frozen importlib._bootstrap_external>", line 978, in _get_parent_path

KeyError: 'python_library'

当库不在子文件夹中时不会发生错误,即

from python_library.test_lib2 import test_func

经常任意运行。但是我有足够的功能,没有子文件夹会很烦人。

这是在 spyder-3.3.2 中发生的,但在 spyder 版本 3.3 中也发生过。0-py36_1。 python 版本是 3.6.4.,spyder 是通过 anaconda 安装和更新的,'python_library' 是通过 setup.py 安装的(setuptools 版本 40.6.3,也出现在版本 39.2 中。0-py36_0).

注:问题出现同样的错误 How do I solve a KeyError when importing a python module? 但是这个问题没有答案,也没有spyder标签。

解决办法是子文件夹tools里没有空的__init__.py文件,只有超级文件夹python_library。将文件 __init__.py 添加到工具中使其工作。

命令行:

cd your_python_file_directory
touch __init__.py

对我有用的解决方案(有类似的错误)是:

问题:执行“import extra.good.best.sigma as sig”时出现 KeyError“extra”

解决方案:

  1. 运行 这个: 导入额外的 sig
  2. 然后这个: 将 extra.good 导入为 sig
  3. 然后这个: 导入 extra.good.best as sig
  4. 然后这个: 将 extra.good.best.sigma 导入为 sig

最后,pycache 文件夹内容似乎自行整理出来了。

当我收到这个错误时,是因为我重组了我的项目并将所有应用程序移动到一个名为 'apps' 的文件夹中。然后,我将 INSTALLED_APPS 列表中的应用名称更改为 'apps.***'。

但是,我忘记了我在 TEMPLATES 设置中有上下文处理器,因此我也需要将应用程序名称更改为 'apps.***'。因此,如果有人在同一条船上,只需按 Ctrl + F 并找到您提到该应用程序的所有其他地方,并确保完整的应用程序名称是正确的。