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
相关产品推荐
相关产品推荐

