首页 > 解决方案 > pathlib.Path.home() 中的 pathlib 库错误:类型对象 'Path' 没有属性 'home'

问题描述

所以我刚刚将 matplotlib 更新到 3.0.2 版本。我可以很好地导入 matplotlib,但是当我尝试时import matplotlib.pyplot,我得到:

---------------------------------------------------------------------------
AttributeError                            
Traceback (most recent call last) <ipython-input-3-864e826dab68> in <module>()
----> 1 import matplotlib.pyplot

/usr/local/lib/python3.6/dist-packages/matplotlib/pyplot.py in <module>()
     30 from cycler import cycler
     31 import matplotlib
---> 32 import matplotlib.colorbar
     33 import matplotlib.image
     34 from matplotlib import rcsetup, style

/usr/local/lib/python3.6/dist-packages/matplotlib/colorbar.py in <module>()
     30 import matplotlib.collections as collections
     31 import matplotlib.colors as colors
---> 32 import matplotlib.contour as contour
     33 import matplotlib.cm as cm
     34 import matplotlib.gridspec as gridspec

/usr/local/lib/python3.6/dist-packages/matplotlib/contour.py in <module>()
     16 import matplotlib.colors as mcolors
     17 import matplotlib.collections as mcoll
---> 18 import matplotlib.font_manager as font_manager
     19 import matplotlib.text as text
     20 import matplotlib.cbook as cbook

/usr/local/lib/python3.6/dist-packages/matplotlib/font_manager.py in <module>()
    133 
    134 if not USE_FONTCONFIG and sys.platform != 'win32':
--> 135     OSXFontDirectories.append(str(Path.home() / "Library/Fonts"))
    136     X11FontDirectories.append(str(Path.home() / ".fonts"))
    137 

AttributeError: type object 'Path' has no attribute 'home'

我在 Ubuntu 18.04 LTS 上,在带有 python3.6.7 的 Jupyter Lab 0.35.4 上。

边信息/问题:在今天早上安装 jupyter lab 之前,我正在使用带有 python3.6.0 的 jupyter notebook。现在内核说它正在使用 python3.6.7,尽管我似乎在我的系统上的任何地方都找不到它。

据说,当我导入不依赖于 matplotlib.pyplot 的任何其他内容时,一切正常。例如,如果我尝试使用 seaborn,它会返回相同的属性错误。

编辑事实上,错误发生在 pathlib 库中。无论我是否在 jupyter 中,都会发生这种情况。要复制它:

from pathlib import Path
Path.home() 

并且错误与以前相同:

AttributeError: type object 'Path' has no attribute 'home'

标签: pythonpython-3.xmatplotlibjupyter-lab

解决方案


如果您的环境包含多个版本的 python,请通过 pip show 检查您的环境当前使用的 pathlib 版本。

pip show pathlib

如果它指向 python <3.5 的 pathlib,请将 PYTHONPATH 修改为指向 python 预期版本的 pathlib。

您可以通过 sys.path 进一步查看 python 包的目录列表。如果它显示比预期版本更早的意外 python 版本的目录,这就是您的环境导入旧 pathlib 的原因。

import sys
sys.path

推荐阅读