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

TeamCity运行Pytest时Matplotlib后端报错问题排查

TeamCity远程构建服务器运行Python单元测试Matplotlib报错解决

问题现象

在TeamCity远程构建服务器上执行包含Matplotlib代码的Python单元测试时失败,报错信息如下:

XXXXX\stats.py:144: in PerformHypothesisTest
    fig, ax = plt.subplots(1, 1, figsize=(10, 6))
.venv\lib\site-packages\matplotlib\pyplot.py:1702: in subplots
    fig = figure(**fig_kw)
.venv\lib\site-packages\matplotlib\pyplot.py:1022: in figure
    manager = new_figure_manager(
.venv\lib\site-packages\matplotlib\pyplot.py:545: in new_figure_manager
    return _get_backend_mod().new_figure_manager(*args, **kwargs)
.venv\lib\site-packages\matplotlib\backend_bases.py:3521: in new_figure_manager
    return cls.new_figure_manager_given_figure(num, fig)
.venv\lib\site-packages\matplotlib\backend_bases.py:3526: in new_figure_manager_given_figure
    return cls.FigureCanvas.new_manager(figure, num)
.venv\lib\site-packages\matplotlib\backend_bases.py:1811: in new_manager
    return cls.manager_class.create_with_canvas(cls, figure, num)
.venv\lib\site-packages\matplotlib\backends\_backend_tk.py:479: in create_with_canvas
    with _restore_foreground_window_at_end():
C:\Python310\lib\contextlib.py:135: in __enter__
    return next(self.gen)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

    @contextmanager
    def _restore_foreground_window_at_end():
>       foreground = _c_internal_utils.Win32_GetForegroundWindow()
E       ValueError: PyCapsule_New called with null pointer

.venv\lib\site-packages\matplotlib\backends\_backend_tk.py:43: ValueError

但测试在以下场景可正常运行:

  • 本地PC通过PyCharm运行
  • 构建服务器通过命令行执行python -m pytest

环境版本

  • Python 3.10.0
  • Matplotlib 3.9.0
  • Pytest 8.2.1
  • 当前Matplotlib后端:tkagg

问题根因

经排查,该问题是Matplotlib 3.9.0版本的bug,在无图形界面的远程构建环境(如TeamCity服务进程)中使用tkagg后端时触发。

临时解决方法

在项目的conftest.py文件中添加以下代码,强制指定Matplotlib使用无界面后端Agg:

import matplotlib
matplotlib.use('Agg')

内容的提问来源于stack exchange,提问作者I. Dunn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 20:22:40