]>
git.saurik.com Git - wxWidgets.git/blob - wxPython/wxversion/wxversion.py
530105427cbea21ac84ab92397d63a8c17e71930
1 #----------------------------------------------------------------------
3 # Purpose: Allows a wxPython program to search for alternate
4 # installations of the wxPython packages and modify sys.path
5 # so they will be found when "import wx" is done.
9 # Created: 24-Sept-2004
11 # Copyright: (c) 2004 by Total Control Software
12 # Licence: wxWindows license
13 #----------------------------------------------------------------------
16 If you have more than one version of wxPython installed this module
17 allows your application to choose which version of wxPython will be
18 imported when it does 'import wx'. You use it like this::
21 wxversion.select('2.4')
24 Or additional build options can also be selected, like this::
27 wxversion.select('2.5.3-unicode')
30 Of course the default wxPython version can also be controlled by
31 setting PYTHONPATH or by editing the wx.pth path configuration file,
32 but using wxversion will allow an application to manage the version
33 selection itself rather than depend on the user to setup the
34 environment correctly.
36 It works by searching the sys.path for directories matching wx-* and
37 then comparing them to what was passed to the select function. If a
38 match is found then that path is inserted into sys.path.
40 NOTE: If you are making a 'bundle' of your application with a tool
41 like py2exe then you should *not* use the wxversion module since it
42 looks at the filesystem for the directories on sys.path, it will fail
43 in a bundled environment. Instead you should simply ensure that the
44 version of wxPython that you want is found by default on the sys.path
45 when making the bundled version by setting PYTHONPATH. Then that
46 version will be included in your bundle and your app will work as
47 expected. Py2exe and the others usually have a way to tell at runtime
48 if they are running from a bundle or running raw, so you can check
49 that and only use wxversion if needed. For example, for py2exe::
51 if not hasattr(sys, 'frozen'):
53 wxversion.select('2.5')
56 More documentation on wxversion and multi-version installs can be
57 found at: http://wiki.wxpython.org/index.cgi/MultiVersionInstalls
61 import sys
, os
, glob
, fnmatch
65 class VersionError(Exception):
68 #----------------------------------------------------------------------
72 Search for a wxPython installation that matches version. If one
73 is found then sys.path is modified so that version will be
74 imported with a 'import wx', otherwise a VersionError exception is
75 raised. This funciton should only be caled once at the begining
76 of the application before wxPython is imported.
78 :param version: Specifies the version to look for, it can
79 either be a string or a list of strings. Each
80 string is compared to the installed wxPythons
81 and the best match is inserted into the
82 sys.path, allowing an 'import wx' to find that
85 The version string is composed of the dotted
86 version number (at least 2 of the 4 components)
87 optionally followed by hyphen ('-') separated
88 options (wx port, unicode/ansi, flavour, etc.) A
89 match is determined by how much of the installed
90 version matches what is given in the version
91 parameter. If the version number components don't
92 match then the score is zero, otherwise the score
93 is increased for every specified optional component
94 that is specified and that matches.
96 if type(versions
) == str:
100 if _selected
is not None:
101 # A version was previously selected, ensure that it matches
104 if _selected
.Score(_wxPackageInfo(ver
)) > 0:
106 # otherwise, raise an exception
107 raise VersionError("A previously selected wx version does not match the new request.")
109 # If we get here then this is the first time wxversion is used,
110 # ensure that wxPython hasn't been imported yet.
111 if sys
.modules
.has_key('wx') or sys
.modules
.has_key('wxPython'):
112 raise VersionError("wxversion.select() must be called before wxPython is imported")
114 # Look for a matching version and manipulate the sys.path as
115 # needed to allow it to be imported.
116 installed
= _find_installed(True)
117 bestMatch
= _get_best_match(installed
, versions
)
119 if bestMatch
is None:
120 raise VersionError("Requested version of wxPython not found")
122 sys
.path
.insert(0, bestMatch
.pathname
)
123 _selected
= bestMatch
125 #----------------------------------------------------------------------
127 def selectNewest(minVersion
):
129 Selects a version of wxPython that has a version number greater
130 than or equal to the version given. If a matching version is not
131 found then instead of raising an exception like select() does this
132 function will inform the user of that fact with a message dialog,
133 open the system's default web browser to the wxPython download
134 page, and then will exit the application.
136 assert type(minVersion
) == str
138 # ensure that wxPython hasn't been imported yet.
139 if sys
.modules
.has_key('wx') or sys
.modules
.has_key('wxPython'):
140 raise VersionError("wxversion.selectNewest() must be called before wxPython is imported")
143 installed
= _find_installed(True)
144 minv
= _wxPackageInfo(minVersion
)
147 # The list is in reverse sorted order, so if the first one is
148 # big enough then choose it
149 if installed
[0] >= minv
:
150 bestMatch
= installed
[0]
152 if bestMatch
is None:
153 import wx
, webbrowser
154 versions
= "\n".join([" "+ver
for ver
in getInstalled()])
155 app
= wx
.PySimpleApp()
156 wx
.MessageBox("This application requires a version of wxPython "
157 "greater than or equal to %s but a matching version "
159 "You currently have these version(s) installed:\n%s"
160 % (minVersion
, versions
),
161 "wxPython Upgrade Needed", style
=wx
.OK
)
163 webbrowser
.open("http://sourceforge.net/project/showfiles.php?group_id=10718")
166 sys
.path
.insert(0, bestMatch
.pathname
)
167 _selected
= bestMatch
170 #----------------------------------------------------------------------
172 def checkInstalled(versions
):
174 Check if there is a version of wxPython installed that matches one
175 of the versions given. Returns True if so, False if not. This
176 can be used to determine if calling `select` will succeed or not.
178 :param version: Same as in `select`, either a string or a list
179 of strings specifying the version(s) to check
183 if type(versions
) == str:
184 versions
= [versions
]
185 installed
= _find_installed()
186 bestMatch
= _get_best_match(installed
, versions
)
187 return bestMatch
is not None
189 #----------------------------------------------------------------------
193 Returns a list of strings representing the installed wxPython
194 versions that are found on the system.
196 installed
= _find_installed()
197 return [os
.path
.basename(p
.pathname
)[3:] for p
in installed
]
201 #----------------------------------------------------------------------
204 def _get_best_match(installed
, versions
):
207 for pkg
in installed
:
209 score
= pkg
.Score(_wxPackageInfo(ver
))
210 if score
> bestScore
:
216 _pattern
= "wx-[0-9].*"
217 def _find_installed(removeExisting
=False):
222 # empty means to look in the current dir
226 # skip it if it's not a package dir
227 if not os
.path
.isdir(pth
):
230 base
= os
.path
.basename(pth
)
232 # if it's a wx path that's already in the sys.path then mark
233 # it for removal and then skip it
234 if fnmatch
.fnmatchcase(base
, _pattern
):
238 # now look in the dir for matching subdirs
239 for name
in glob
.glob(os
.path
.join(pth
, _pattern
)):
240 # make sure it's a directory
241 if not os
.path
.isdir(name
):
243 # and has a wx subdir
244 if not os
.path
.exists(os
.path
.join(name
, 'wx')):
246 installed
.append(_wxPackageInfo(name
, True))
250 del sys
.path
[sys
.path
.index(rem
)]
257 class _wxPackageInfo(object):
258 def __init__(self
, pathname
, stripFirst
=False):
259 self
.pathname
= pathname
260 base
= os
.path
.basename(pathname
)
261 segments
= base
.split('-')
263 segments
= segments
[1:]
264 self
.version
= tuple([int(x
) for x
in segments
[0].split('.')])
265 self
.options
= segments
[1:]
268 def Score(self
, other
):
271 # whatever number of version components given in other must
273 minlen
= min(len(self
.version
), len(other
.version
))
274 if self
.version
[:minlen
] != other
.version
[:minlen
]:
278 for opt
in other
.options
:
279 if opt
in self
.options
:
285 def __lt__(self
, other
):
286 return self
.version
< other
.version
or \
287 (self
.version
== other
.version
and self
.options
< other
.options
)
288 def __le__(self
, other
):
289 return self
.version
<= other
.version
or \
290 (self
.version
== other
.version
and self
.options
<= other
.options
)
292 def __gt__(self
, other
):
293 return self
.version
> other
.version
or \
294 (self
.version
== other
.version
and self
.options
> other
.options
)
295 def __ge__(self
, other
):
296 return self
.version
>= other
.version
or \
297 (self
.version
== other
.version
and self
.options
>= other
.options
)
299 def __eq__(self
, other
):
300 return self
.version
== other
.version
and self
.options
== other
.options
304 #----------------------------------------------------------------------
306 if __name__
== '__main__':
316 savepath
= sys
.path
[:]
320 print "Asked for %s:\t got: %s" % (version
, sys
.path
[0])
321 #pprint.pprint(sys.path)
325 sys
.path
= savepath
[:]
330 # make some test dirs
333 'wx-2.5.2.9-gtk2-unicode',
334 'wx-2.5.2.9-gtk-ansi',
336 'wx-2.5.2.8-gtk2-unicode',
339 d
= os
.path
.join('/tmp', name
)
341 os
.mkdir(os
.path
.join(d
, 'wx'))
343 # setup sys.path to see those dirs
344 sys
.path
.append('/tmp')
348 pprint
.pprint( getInstalled())
349 print checkInstalled("2.4")
350 print checkInstalled("2.5-unicode")
351 print checkInstalled("2.99-bogus")
359 # There isn't a unicode match for this one, but it will give the best
360 # available 2.4. Should it give an error instead? I don't think so...
363 # Try asking for multiple versions
364 test(["2.6", "2.5.3", "2.5.2-gtk2"])
367 # expecting an error on this one
369 except VersionError
, e
:
370 print "Asked for 2.6:\t got Exception:", e
372 # check for exception when incompatible versions are requested
376 except VersionError
, e
:
377 print "Asked for incompatible versions, got Exception:", e
381 d
= os
.path
.join('/tmp', name
)
382 os
.rmdir(os
.path
.join(d
, 'wx'))