我收到了
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标签。
解决方案是子文件夹工具中没有空的__init__.py
文件,只在超级文件夹python_library中。将文件__init__.py
添加到工具中使其工作。
命令行:
cd your_python_file_position
touch __init__.py