Bypass Matplotlib plotting during continuous integration

less than 1 minute read

It’s useful to not plot on continuous integration systems such as Travis CI, AppVeyor, GitLab, etc. In many cases the CI doesn’t have an X11 desktop. There are two main ways to accomplish this:

  • if statement(s) in the Python code to detect CI via environment variable, totally avoiding generating plots
  • generate plots, but use xvfb dummy X11 desktop

The xvfb method is a more complete test of your code and is easier to implement.

Xvfb

This method is more robust and recommended.

Add to your .travis.yml:

# Fake X11 server
before_script:
  - "export DISPLAY=:99.0"
  - "sh -e /etc/init.d/xvfb start"
  - sleep 3 # give xvfb some time to start

Detect CI inside Python

Put self-test Python code that plots AND the matplotlib import under this if statement:

import os

CI = bool(os.environ['CI']) if 'CI' in os.environ else False

def test_myfun():
    if not CI:
        from matplotlib.pyplot import figure,show

        ...

Notes

CI Environment variables

These CI’s and more set the environment variable CI as a de facto standard for easy CI detection. Here are a few listings of CI system environment variables for reference:

Leave a Comment