We're updating the default styles for Matplotlib 2.0

Learn what to expect in the new updates


Previous topic

tests Examples

Next topic

text_labels_and_annotations Examples

This Page

tests example code: backend_driver.pyΒΆ

[source code]

#!/usr/bin/env python

from __future__ import print_function, division
This is used to drive many of the examples across the backends, for
regression testing, and comparing backend efficiency.

You can specify the backends to be tested either via the --backends
switch, which takes a comma-separated list, or as separate arguments,

    python backend_driver.py agg ps

would test the agg and ps backends. If no arguments are given, a
default list of backends will be tested.

Interspersed with the backend arguments can be switches for the Python
interpreter executing the tests. If entering such arguments causes an
option parsing error with the driver script, separate them from driver
switches with a --.

import os
import time
import sys
import glob
from optparse import OptionParser

import matplotlib.rcsetup as rcsetup
from matplotlib.cbook import Bunch, dedent

all_backends = list(rcsetup.all_backends)  # to leave the original list alone

# actual physical directory for each dir
dirs = dict(files=os.path.join('..', 'lines_bars_and_markers'),
            shapes=os.path.join('..', 'shapes_and_collections'),
            images=os.path.join('..', 'images_contours_and_fields'),
            pie=os.path.join('..', 'pie_and_polar_charts'),
            text=os.path.join('..', 'text_labels_and_annotations'),
            ticks=os.path.join('..', 'ticks_and_spines'),
            subplots=os.path.join('..', 'subplots_axes_and_figures'),
            specialty=os.path.join('..', 'specialty_plots'),
            showcase=os.path.join('..', 'showcase'),
            pylab = os.path.join('..', 'pylab_examples'),
            api = os.path.join('..', 'api'),
            units = os.path.join('..', 'units'),
            mplot3d = os.path.join('..', 'mplot3d'))

# files in each dir
files = dict()

files['lines'] = [

files['shapes'] = [

files['colors'] = [

files['images'] = [

files['statistics'] = [

files['pie'] = [

files['text_labels_and_annotations'] = [

files['ticks_and_spines'] = [

files['subplots_axes_and_figures'] = [

files['showcase'] = [

files['pylab'] = [


files['api'] = [

files['units'] = [
    #'artist_tests.py',  # broken, fixme
    #'bar_unit_demo.py', # broken, fixme
    #'ellipse_with_units.py',  # broken, fixme
    #'units_scatter.py', # broken, fixme


files['mplot3d'] = [

# dict from dir to files we know we don't want to test (e.g., examples
# not using pyplot, examples requiring user input, animation examples,
# examples that may only work in certain environs (usetex examples?),
# examples that generate multiple figures

excluded = {
    'pylab' : ['__init__.py', 'toggle_images.py',],
    'units' : ['__init__.py', 'date_support.py',],

def report_missing(dir, flist):
    'report the py files in dir that are not in flist'
    globstr = os.path.join(dir, '*.py')
    fnames = glob.glob(globstr)

    pyfiles = set([os.path.split(fullpath)[-1] for fullpath in set(fnames)])

    exclude = set(excluded.get(dir, []))
    flist = set(flist)
    missing = list(pyfiles-flist-exclude)
    if missing:
        print ('%s files not tested: %s'%(dir, ', '.join(missing)))

def report_all_missing(directories):
    for f in directories:
        report_missing(dirs[f], files[f])

# tests known to fail on a given backend

failbackend = dict(
    svg = ('tex_demo.py', ),
    agg = ('hyperlinks.py', ),
    pdf = ('hyperlinks.py', ),
    ps = ('hyperlinks.py', ),

    import subprocess
    def run(arglist):
            ret = subprocess.call(arglist)
        except KeyboardInterrupt:
            return ret
except ImportError:
    def run(arglist):
        os.system(' '.join(arglist))

def drive(backend, directories, python=['python'], switches = []):
    exclude = failbackend.get(backend, [])

    # Clear the destination directory for the examples
    path = backend
    if os.path.exists(path):
        import glob
        for fname in os.listdir(path):
            os.unlink(os.path.join(path, fname))
    failures = []

    testcases = [os.path.join(dirs[d], fname)
                 for d in directories
                 for fname in files[d]]

    for fullpath in testcases:
        print ('\tdriving %-40s' % (fullpath)),
        fpath, fname = os.path.split(fullpath)

        if fname in exclude:
            print ('\tSkipping %s, known to fail on backend: %s'%backend)

        basename, ext = os.path.splitext(fname)
        outfile = os.path.join(path, basename)
        tmpfile_name = '_tmp_%s.py' % basename
        tmpfile = open(tmpfile_name, 'w')

        future_imports = 'from __future__ import division, print_function'
        for line in open(fullpath):
            line_lstrip = line.lstrip()
            if line_lstrip.startswith("#"):
            elif 'unicode_literals' in line:
                future_imports = future_imports + ', unicode_literals'

            'import sys\n',
            'sys.path.append("%s")\n' % fpath.replace('\\', '\\\\'),
            'import matplotlib\n',
            'matplotlib.use("%s")\n' % backend,
            'from pylab import savefig\n',
            'import numpy\n',
        for line in open(fullpath):
            line_lstrip = line.lstrip()
            if (line_lstrip.startswith('from __future__ import') or
                line_lstrip.startswith('matplotlib.use') or
                line_lstrip.startswith('savefig') or
        if backend in rcsetup.interactive_bk:
            tmpfile.write('\nsavefig(r"%s", dpi=150)' % outfile)

        start_time = time.time()
        program = [x % {'name': basename} for x in python]
        ret = run(program + [tmpfile_name] + switches)
        end_time = time.time()
        print ("%s %s" % ((end_time - start_time), ret))
        #os.system('%s %s %s' % (python, tmpfile_name, ' '.join(switches)))
        if ret:
    return failures

def parse_options():
    doc = (__doc__ and __doc__.split('\n\n')) or "  "
    op = OptionParser(description=doc[0].strip(),
                      usage='%prog [options] [--] [backends and switches]',
                      #epilog='\n'.join(doc[1:])  # epilog not supported on my python2.4 machine: JDH
                    clean=False, coverage=False, valgrind=False)
    op.add_option('-d', '--dirs', '--directories', type='string',
                  dest='dirs', help=dedent('''
      Run only the tests in these directories; comma-separated list of
      one or more of: pylab (or pylab_examples), api, units, mplot3d'''))
    op.add_option('-b', '--backends', type='string', dest='backends',
      Run tests only for these backends; comma-separated list of
      one or more of: agg, ps, svg, pdf, template, cairo,
      Default is everything except cairo.'''))
    op.add_option('--clean', action='store_true', dest='clean',
                  help='Remove result directories, run no tests')
    op.add_option('-c', '--coverage', action='store_true', dest='coverage',
                  help='Run in coverage.py')
    op.add_option('-v', '--valgrind', action='store_true', dest='valgrind',
                  help='Run in valgrind')

    options, args = op.parse_args()
    switches = [x for x in args if x.startswith('--')]
    backends = [x.lower() for x in args if not x.startswith('--')]
    if options.backends:
        backends += [be.lower() for be in options.backends.split(',')]

    result = Bunch(
        dirs = options.dirs.split(','),
        backends = backends or ['agg', 'ps', 'svg', 'pdf', 'template'],
        clean = options.clean,
        coverage = options.coverage,
        valgrind = options.valgrind,
        switches = switches)
    if 'pylab_examples' in result.dirs:
        result.dirs[result.dirs.index('pylab_examples')] = 'pylab'
    #print result
    return (result)

if __name__ == '__main__':
    times = {}
    failures = {}
    options = parse_options()

    if options.clean:
        localdirs = [d for d in glob.glob('*') if os.path.isdir(d)]
        all_backends_set = set(all_backends)
        for d in localdirs:
            if d.lower() not in all_backends_set:
            print ('removing %s'%d)
            for fname in glob.glob(os.path.join(d, '*')):
        for fname in glob.glob('_tmp*.py'):

        print ('all clean...')
        raise SystemExit
    if options.coverage:
        python = ['coverage.py', '-x']
    elif options.valgrind:
        python = ['valgrind', '--tool=memcheck', '--leak-check=yes',
                  '--log-file=%(name)s', sys.executable]
    elif sys.platform == 'win32':
        python = [sys.executable]
        python = [sys.executable]

    for backend in options.backends:
        print ('testing %s %s' % (backend, ' '.join(options.switches)))
        t0 = time.time()
        failures[backend] = \
            drive(backend, options.dirs, python, options.switches)
        t1 = time.time()
        times[backend] = (t1-t0)/60.0

    # print times
    for backend, elapsed in times.items():
        print ('Backend %s took %1.2f minutes to complete' % (backend, elapsed))
        failed = failures[backend]
        if failed:
            print ('  Failures: %s' % failed)
        if 'template' in times:
            print ('\ttemplate ratio %1.3f, template residual %1.3f' % (
                elapsed/times['template'], elapsed-times['template']))

Keywords: python, matplotlib, pylab, example, codex (see Search examples)