在鼻子测试期间使用 'Agg'

Using 'Agg' during nosetests

我有一个单元测试,用于测试创建一些绘图的函数。我不希望为这些图创建图形,因此我将 matlplotlib.use('Agg') 添加到 单元测试 函数 中。

单元测试和函数的第一两行:

import matplotlib as mpl
mpl.use('Agg')

...我仍然收到此消息:

This call to matplotlib.use() has no effect
because the backend has already been chosen;
matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.

...当我 运行:

nosetests my_unit_test.py

nosetests 运行 在我的单元测试之前 运行 目录中的其他代码吗?

正如@Chris 所建议的,我添加上面的评论作为答案,以防其他人遇到同样的问题。似乎解决方案是更改 .matplotlibrc 文件中的默认后端(请参阅 matplotlib.org/users/customizing.html)。由于后端在导入时设置为默认值,因此在存储在单元测试目录中的 .matplotlibrc 中指定正确的后端似乎可以解决问题。注意,系统先检查本地文件夹,如果在本地找不到,则默认为系统.matplotlibrc。这样,自定义默认文件可以包含在单元测试中。