I am trying to create a standalone application using py2exe that depends on matplotlib and numpy. The code of the application is this:
import numpy as np
import pylab as plt
plt.figure()
a = np.random.random((16,16))
plt.imshow(a,interpolation='nearest')
plt.show()
The setup code for py2exe (modified from http://www.py2exe.org/index.cgi/MatPlotLib) is this:
from distutils.core import setup
import py2exe
import sys
sys.argv.append('py2exe')
opts = {
'py2exe': {"bundle_files" : 3,
"includes" : [ "matplotlib.backends",
"matplotlib.backends.backend_qt4agg",
"pylab", "numpy",
"matplotlib.backends.backend_tkagg"],
'excludes': ['_gtkagg', '_tkagg', '_agg2',
'_cairo', '_cocoaagg',
'_fltkagg', '_gtk', '_gtkcairo', ],
'dll_excludes': ['libgdk-win32-2.0-0.dll',
'libgobject-2.0-0.dll']
}
}
setup(console=[{"script" : "matplotlib_test.py"}],
zipfile=None,options=opts)
Now, when bundle_files is set = 3 or is absent, all works fine, but the resulting exe cannot be distributed to a machine that is not configured with the same version of Python, etc. If I set bundle_files = 1, it creates a suitably large exe file that must have everything bundled, but it fails to run locally or distributed. In this case, I'm creating everything on a Windows 7 machine with Python 2.6.6 and trying to run locally and on an XP machine with Python 2.6.4 installed.
The errors I get when running on the XP machine seem strange since, without bundling, I get no errors on Win 7. With bundling, Win 7 does not report the traceback information, so I cannot be sure the errors are the same. In any case, here's the error message on XP:
Traceback (most recent call last):
File "matplotlib_test.py", line 2, in <module>
File "zipextimporter.pyc", line 82, in load_module
File "pylab.pyc", line 1, in <module>
File "zipextimporter.pyc", line 82, in load_module
File "matplotlib\__init__.pyc", line 709, in <module>
File "matplotlib\__init__.pyc", line 627, in rc_params
File "matplotlib\__init__.pyc", line 565, in matplotlib_fname
File "matplotlib\__init__.pyc", line 240, in wrapper
File "matplotlib\__init__.pyc", line 439, in _get_configdir
RuntimeError: Failed to create C:\Documents and Settings\mnfienen/.matplotlib; c
onsider setting MPLCONFIGDIR to a writable directory for matplotlib configuratio
n data
Many thanks in advance if anyone can point me in a direction that will fix this!
EDIT 1:
I followed William's advice and fixed the problem with MPLCONFIGDIR, but now get a new error:
:Traceback (most recent call last):
File "matplotlib\__init__.pyc", line 479, in _get_data_path
RuntimeError: Could not find the matplotlib data files
EDIT 2:
I fixed the data files problem by using:
data_files=matplotlib.get_py2exe_datafiles()
This leads to a new error:
Traceback (most recent call last):
File "matplotlib_test.py", line 5, in <module>
import matplotlib.pyplot as plt
File "matplotlib\pyplot.pyc", line 78, in <module>
File "matplotlib\backends\__init__.pyc", line 25, in pylab_setup
ImportError: No module named backend_wxagg
I had the same problem. I think the problem was caused by pylab in matplotlib, py2exe seemed to have trouble finding and getting all the backends associated with pylab.
I got around the problem by changing all my embedded plots to use matplotlib.figure instead of pylab. Here's a simple example on how to make a plot with matplotlib.figure:
import matplotlib.figure as fg
import numpy as np
fig = fg.Figure()
ax = fig.add_subplot(111)
lines = ax.plot(range(10), np.random.randn(10), range(10), np.random.randn(10))
You cannot use fig.show() directly with this, but it can be embedded in GUIs. I used Tkinker:
canvas = FigureCanvasTkAgg(fig, canvas_master)
canvas.show()
Well Misha Fienen, I guess it seems to be failing to write to your user folder, which you probably already knew. Just a stab in the dark but have you tried testing what happens if you follow the advice and change MPLCONFIGDIR to something a bit more basic (eg. "C:\matlibplotcfg\")?
There are two ways of solving the problem.
1.- In your matplotlib.rc file use:
backend : TkAgg
2.- alternatively, in your setup.py "includes" key add:
"matplotlib.backends.backend_wxagg"
both ways produce the test figure in Python 2.6, windows XP
Related
I am encountering an error in MetPy when following the geocolor satellite imagery tutorial. Specifically, the section entitled "Plot with Cartopy Geostationary Projection". This breakage occurred roughly two weeks ago and functionality has yet to return. Consider the following code:
from xarray import open_dataset
import metpy
data_dir = '.'
color_file = 'OR_ABI-L1b-RadC-M3C01_G16_s20180152002235_e20180152005008_c20180152005054.nc'
c = open_dataset('/'.join([data_dir,color_file]))
dat = c.metpy.parse_cf('Rad')
This block is functionally similar to that provided in the MetPy geocolor satellite tutorial. It worked fine until recently. Now the following error occurs:
Traceback (most recent call last):
File "<stdin>", line 1, in module
File "/usr/local/anaconda3/lib/python3.7/site-packages/metpy/xarray.py", line 191, in parse_cf
from .plots.mapping import CFProjection
File "/usr/local/anaconda3/lib/python3.7/site-packages/metpy/plots/__init__.py", line 13, in module
from .skewt import * # noqa: F403
File "/usr/local/anaconda3/lib/python3.7/site-packages/metpy/plots/skewt.py", line 28, in module
from ..calc import dewpoint, dry_lapse, moist_lapse, vapor_pressure
File "/usr/local/anaconda3/lib/python3.7/site-packages/metpy/calc/__init__.py", line 7, in module
from .cross_sections import * # noqa: F403
File "/usr/local/anaconda3/lib/python3.7/site-packages/metpy/calc/cross_sections.py", line 14, in module
from .tools import first_derivative
File "/usr/local/anaconda3/lib/python3.7/site-packages/metpy/calc/tools.py", line 101, in module
def find_intersections(x, a, b, direction='all'):
File "/usr/local/anaconda3/lib/python3.7/site-packages/pint/registry_helpers.py", line 248, in decorator
% (func.__name__, count_params, len(args))
TypeError: find_intersections takes 4 parameters, but 3 units were passed
What seems to be the problem here? Is there a workaround available?
I think it's an incompatibility between your installed versions of MetPy and Pint. Try making sure you're running the latest versions of those two with:
conda update metpy pint
I should note that MetPy 0.12.0 (currently the latest) is incompatible with xarray 0.15.1. As of this writing, if the above command updates xarray, you'll need to roll it back slightly with:
conda install xarray=0.15.0
We're working on a bugfix release to address this.
I'm on an osx machine. Matplotlib was working fine a few days back, but today when i wanted to use it it just won't import. There are a bunch of lines and at the bottom it gives me a type error goes on about a copy function needing another variable. I've tried reinstalling it and still wont budge. any thoughts? I'm still fairly new to this so i have no idea whats going on.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/__init__.py", line 138, in <module>
from . import cbook, rcsetup
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/rcsetup.py", line 24, in <module>
from matplotlib.fontconfig_pattern import parse_fontconfig_pattern
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/matplotlib/fontconfig_pattern.py", line 18, in <module>
from pyparsing import (Literal, ZeroOrMore, Optional, Regex, StringEnd,
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pyparsing.py", line 5658, in <module>
_reBracketExpr = Literal("[") + Optional("^").setResultsName("negate") + Group(OneOrMore(_charRange | _singleChar)).setResultsName("body") + "]"
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pyparsing.py", line 1480, in setResultsName
return self._setResultsName(name, listAllMatches)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pyparsing.py", line 1483, in _setResultsName
newself = self.copy()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pyparsing.py", line 1437, in copy
cpy = copy.copy(self)
TypeError: copy() missing 2 required positional arguments: 'E' and 'X'
Not sure if it's related, but when I migrated to OSX I had problems with matplotlib which were solved by changing the backend:
import matplotlib
matplotlib.use("MacOSX")
Thanks for the response, it turns out matplotlib didn't like the directory I was in, which is odd. Just changing where i was trying to run it from worked.
I am running my python script in another machine by using ssh command in linux. I have also run this command :
source ~/.bashrc
after logging in the other machine, in order to define the proper paths in the new machine. I was getting the error message for running the following python code lines even I have tried to follow the instruction in this question by defining the backend.
>>> import matplotlib
>>> import pylab as plt
>>> matplotlib.use('Agg')
>>> import numpy as np
>>> x=np.arange(0,2,0.001)
>>> y=np.sin(x)**2+4*np.cos(x)
>>> fig = plt.figure()
>>> plt.plot(x,y,'r.')
The error message
This probably means that Tcl wasn't installed properly.
Traceback (most recent call last):
File "Systematic_Optimised.py", line 513, in <module>
fig = plt.figure()
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py", line 435, in figure
**kwargs)
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py", line 47, in new_figure_manager
return new_figure_manager_given_figure(num, thisFig)
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py", line 54, in new_figure_manager_given_figure
canvas = FigureCanvasQTAgg(figure)
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py", line 72, in __init__
FigureCanvasQT.__init__(self, figure)
File "/vol/aibn84/data2/zahra/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4.py", line 68, in __init__
_create_qApp()
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt5.py", line 138, in _create_qApp
raise RuntimeError('Invalid DISPLAY variable')
RuntimeError: Invalid DISPLAY variable
any suggestion how to fix the problem
You must declare matplotlib.use('agg') before import pylab as plt.
Reference
Add
plt.switch_backend('agg')
after
import matplotlib.pyplot as plt
So I downloaded and installed matplotlib. The weird things is that I can run the examples fine when they were placed in home/user/Desktop but when I moved them to home/user/Documents, they stopped working and I get the below message. Is there something special about the Documents folder that they prevent matplotlib from importing?
Traceback (most recent call last):
File "contour_manual.py", line 4, in <module>
import matplotlib.pyplot as plt
File "/usr/local/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 23, in <module>
from matplotlib.figure import Figure, figaspect
File "/usr/local/lib/python2.7/dist-packages/matplotlib/figure.py", line 18, in <module>
from axes import Axes, SubplotBase, subplot_class_factory
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes.py", line 8454, in <module>
Subplot = subplot_class_factory()
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes.py", line 8446, in subplot_class_factory
new_class = new.classobj("%sSubplot" % (axes_class.__name__),
AttributeError: 'module' object has no attribute 'classobj'
Do you have a file new.py in your Documents folder, by any chance? If you have, try renaming it to something else.
The matplotlib module axes.py imports new, and if you have a file new.py lying around in your Documents folder, that will cause Python to load it instead of the built-in new module.
Im using PyMel to write up some tools, but as of yesterday my PyMel modules won't source, due to an error that I get during import:
import pymel.core as pm
# pymel.core : Updating pymel with pre-loaded plugins: OpenEXRLoader, DirectConnect, mayaHIK, ikSpringSolver, Mayatomr, decomposeMatrix, tiffFloatReader, VectorRender, studioImport, mayaCharacterization, rotateHelper, MayaCryExport22012-x64, Substance, MayaMuscle, fbxmaya, ik2Bsolver #
# pop from empty list
# Traceback (most recent call last):
# File "<maya console>", line 1, in <module>
# File "C:\Program Files\Autodesk\Maya2012\Python\lib\site-packages\pymel-1.0.0-py2.6.egg\pymel\core\__init__.py", line 250, in <module>
# _installCallbacks()
# File "C:\Program Files\Autodesk\Maya2012\Python\lib\site-packages\pymel-1.0.0-py2.6.egg\pymel\core\__init__.py", line 248, in _installCallbacks
# _pluginLoaded( plugin )
# File "C:\Program Files\Autodesk\Maya2012\Python\lib\site-packages\pymel-1.0.0-py2.6.egg\pymel\core\__init__.py", line 79, in _pluginLoaded
# _factories.cmdlist[funcName] = _factories.cmdcache.getCmdInfoBasic( funcName )
# File "C:\Program Files\Autodesk\Maya2012\Python\lib\site-packages\pymel-1.0.0-py2.6.egg\pymel\internal\cmdcache.py", line 212, in getCmdInfoBasic
# synopsis = lines.pop(0)
# IndexError: pop from empty list #
any ideas on how to fix this? I downloaded the newest version of PyMel, checked the install guide if I left anything out (i used method 2), but i still have no idea what the problem is.
Thx,
Nils
Alright, so after trying to re-install most of my programs I simply fixed the cdmcashe.py from where the error comes from - I ddnt originally want to do this because I wasnt sure what I might break, but after over 2 weeks of trying things out I just went for broke:
If anyone else has this problem, all u need to do is open your cmdcache.py and add an if test to line 212
if lines:
That'll just fix it.
yeah. simple as that. Imagine the head->desking session I had after doing that.