我收到
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。,通过anaconda安装和更新了spyder,并通过setup.py(setuptools版本40.6.3,也出现在39.2.0-py36_0版本中)安装了“ python_library”。
注意:出现相同的错误 How do I solve a KeyError when importing a python module? 但是这个问题没有答案,也没有spyder标签。
答案 0 :(得分:2)
解决方案是,子文件夹工具中没有空的__init__.py
文件,只有超级文件夹python_library中没有。将文件__init__.py
添加到工具中即可正常工作。
答案 1 :(得分:0)
命令行:
cd your_python_file_position
touch __init__.py
答案 2 :(得分:0)
对我有用的解决方案(有类似的错误)是:
问题:执行“import extra.good.best.sigma as sig”时出现KeyError“extra”
解决方案:
最后 pycache 文件夹的内容似乎自己整理出来了。