Skip to main content
 首页 » 编程设计

python之pathlib.Path.home() 中的 pathlib 库错误 : type object 'Path' has no attribute 'home'

2024年11月24日15unruledboy

所以我刚刚将 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 上,在 Jupyter Lab 0.35.4 和 python3.6.7 上。

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

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

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

from pathlib import Path 
Path.home()  

错误和之前一样:

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

请您参考如下方法:

我最近遇到了这个问题,matplotlib 试图导入和使用 pathlib 但失败了,因为我的 virtualenv 是 3.6,但它以某种方式获得了 3.4 pathlib 并遇到了你遇到的异常或它正在调用的 mkdir() 的另一个异常缺少 exists_ok 可选参数。

事实证明,我使用的其中一个模块 openapi-spec-validator 版本 0.2.6 下载了 pathlib 的副本(3.4 类型)并将其粘贴在基本站点包文件夹中,它可以轻松地在其中最终被 matplotlib 而不是标准库版本使用。在我的例子中,升级到 0.2.7 修复了它,因为该版本不会下载并将文件放在那里。

但是,如果您没有使用 openapi-spec-validator 并且遇到了这个问题,请检查您的环境中是否有额外的 pathlib.py 副本。