You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

导入matplotlib时触发AttributeError:module 'logging' has no attribute 'getLogger'的问题求助

解决matplotlib导入时的循环导入错误(AttributeError: partially initialized module 'logging' has no attribute 'getLogger')

这绝对不是matplotlib的bug,问题根源出在你的脚本文件名上!

看报错信息里的关键路径:

File "D:\programs\python\string.py", line 1, in
import matplotlib.pyplot as plt

Python在导入标准库的string模块时,错误地加载了你自己写的string.py文件,而不是Python自带的string模块。这就引发了循环导入的连锁反应:

  1. 你运行自己的string.py,开始导入matplotlib.pyplot
  2. matplotlib内部会导入logging模块
  3. logging模块需要导入标准库的string.Template,但因为你的脚本和标准库模块同名,Python优先加载了你的string.py
  4. 你的脚本又再次导入matplotlib.pyplot,形成循环,此时logging模块还没完成初始化,就抛出了AttributeError

快速解决方案:

  • 重命名你的脚本文件:把string.py改成和标准库模块不冲突的名字,比如matplotlib_test.py或者my_plot_script.py
  • 删除缓存文件:检查脚本所在目录下有没有生成string.pyc文件(如果有),务必删掉它,避免Python加载旧的缓存
  • 重新运行脚本:完成上面两步后,再执行改名后的脚本,应该就能正常导入matplotlib了

这种因为脚本文件名和标准库模块重名导致的导入错误很常见,以后写Python脚本时尽量避开用string、logging、sys这类标准库模块名当文件名哦。

内容的提问来源于stack exchange,提问作者Brain Stroke Patient

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 03:59:10