how to freeze your matplotlib apps using py2exe

In order to "freeze" your matplotlib-0.51 application using the Agg
backend into a standalone executable, the following are the steps you
should take:

1. Write your setup.py file that py2exe will use for compiling. Example:

    # setup.py
    from distutils.core import setup
    import py2exe
    import glob
  
    data = glob.glob(r'C:\Python23\share\matplotlib\*')

    setup(
        console=["your_file.py"],
        data_files=[("share",data)]
    )

. Note that we use "data" here to copy the matplotlibdata "share" folder
contents into your /dist/share directory.

2. Insert the following import statements into your_file.py, which is
the file containing your matplotlib code:

    import matplotlib
    import matplotlib.ft2font
    import matplotlib.backends.backend_agg
    import ttfquery
    from matplotlib.matlab import *
    
3. Now we must take care of fonts. We're assuming that the machine we're
installing to doesn't have the MATPLOTLIBDATA or TTFPATH environment
variables set, so we must do the following:

    In ttfquery\_scriptregistry.py comment out these lines:

    ### more robust registry-file location by John Hunter...
    #if os.environ.has_key('HOME'):
    # registryFile = os.path.join( os.environ['HOME'], ".font.cache")
    #else:
  # OpenGLContext uses the Application Data directory for win32,
  # should consider porting that code here...
      # registryFile = os.path.join( os.path.split(__file__)[0],
"font.cache")

    And replace with:

    registryFile = r'share\.font.cache'

    In matplotlib\__init__.py comment out these lines in the
get_data_path() method:

     #path = os.path.join(distutils.sysconfig.PREFIX, 'share',
'matplotlib')
        #if os.path.isdir(path): return path

            #path =
os.path.join(os.sep.join(__file__.split(os.sep)[:-5]),
    # 'share','matplotlib')
    #if os.path.isdir(path): return path

    #if os.environ.has_key('MATPLOTLIBDATA'):
    # path = os.environ['MATPLOTLIBDATA']
    # if os.path.isdir(path): return path
    #raise RuntimeError('Could not find the matplotlib data files')

    And replace with:

    return 'share'

    Also, while you have __init__.py open, in defaultParams you should
change the default backend to 'Agg' and
    default fontname to 'Vera' since it ships with matplotlib.

4. Copy your .font.cache file from /ttfquery into your matplotlibdata
/share directory. Your system did a system scan of fonts to generate
this file the first time that Agg was run but your "clean" system won't
have it. By copying it to share, py2exe will include it in the generated
/dist/share directory.

That should be it. Many thanks to John Hunter for helping me hack
through this, and I hope this information will find its way to others so
it can save them lots of time.

--Matt