]> git.saurik.com Git - wxWidgets.git/blob - wxPython/wxversion/wxversion.py
26c15e62c2fbcd3e0dc485104965a847a66971d7
[wxWidgets.git] / wxPython / wxversion / wxversion.py
1 #----------------------------------------------------------------------
2 # Name: wxversion
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.
6 #
7 # Author: Robin Dunn
8 #
9 # Created: 24-Sept-2004
10 # RCS-ID: $Id$
11 # Copyright: (c) 2004 by Total Control Software
12 # Licence: wxWindows license
13 #----------------------------------------------------------------------
14
15 """
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::
19
20 import wxversion
21 wxversion.select('2.4')
22 import wx
23
24 Or additional build options can also be selected, like this::
25
26 import wxversion
27 wxversion.select('2.5.3-unicode')
28 import wx
29
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.
35
36 It works by searching the sys.path for directories matching wx-* and
37 then comparing them to what was passed to the require function. If a
38 match is found then that path is inserted into sys.path.
39
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 filesystem for the directories on sys.path, it will fail in a
43 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::
50
51 if not hasattr(sys, 'frozen'):
52 import wxversion
53 wxversion.select('2.5')
54 import wx
55
56 More documentation on wxversion and multi-version installs can be
57 found at: http://wiki.wxpython.org/index.cgi/MultiVersionInstalls
58
59 """
60
61 import sys, os, glob, fnmatch
62
63
64 _selected = None
65 class VersionError(Exception):
66 pass
67
68 #----------------------------------------------------------------------
69
70 def select(versions):
71 """
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.
77
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
83 version.
84
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.
95 """
96 if type(versions) == str:
97 versions = [versions]
98
99 global _selected
100 if _selected is not None:
101 # A version was previously selected, ensure that it matches
102 # this new request
103 for ver in versions:
104 if _selected.Score(_wxPackageInfo(ver)) > 0:
105 return
106 # otherwise, raise an exception
107 raise VersionError("A previously selected wx version does not match the new request.")
108
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.require() must be called before wxPython is imported")
113
114 # Look for a matching version and manipulate the sys.path as
115 # needed to allow it to be imported.
116 packages = _find_installed(True)
117 bestMatch = _get_best_match(packages, versions)
118
119 if bestMatch is None:
120 raise VersionError("Requested version of wxPython not found")
121
122 sys.path.insert(0, bestMatch.pathname)
123 _selected = bestMatch
124
125 #----------------------------------------------------------------------
126
127 def checkInstalled(versions):
128 """
129 Check if there is a version of wxPython installed that matches one
130 of the versions given. Returns True if so, False if not. This
131 can be used to determine if calling `select` will succeed or not.
132
133 :param version: Same as in `select`, either a string or a list
134 of strings specifying the version(s) to check
135 for.
136 """
137
138 if type(versions) == str:
139 versions = [versions]
140 packages = _find_installed()
141 bestMatch = _get_best_match(packages, versions)
142 return bestMatch is not None
143
144 #----------------------------------------------------------------------
145
146 def getInstalled():
147 """
148 Returns a list of strings representing the installed wxPython
149 versions that are found on the system.
150 """
151 packages = _find_installed()
152 return [os.path.basename(p.pathname)[3:] for p in packages]
153
154
155
156 #----------------------------------------------------------------------
157 # private helpers...
158
159 def _get_best_match(packages, versions):
160 bestMatch = None
161 bestScore = 0
162 for pkg in packages:
163 for ver in versions:
164 score = pkg.Score(_wxPackageInfo(ver))
165 if score > bestScore:
166 bestMatch = pkg
167 bestScore = score
168 return bestMatch
169
170
171 _pattern = "wx-[0-9].*"
172 def _find_installed(removeExisting=False):
173 installed = []
174 toRemove = []
175 for pth in sys.path:
176
177 # empty means to look in the current dir
178 if not pth:
179 pth = '.'
180
181 # skip it if it's not a package dir
182 if not os.path.isdir(pth):
183 continue
184
185 base = os.path.basename(pth)
186
187 # if it's a wx path that's already in the sys.path then mark
188 # it for removal and then skip it
189 if fnmatch.fnmatchcase(base, _pattern):
190 toRemove.append(pth)
191 continue
192
193 # now look in the dir for matching subdirs
194 for name in glob.glob(os.path.join(pth, _pattern)):
195 # make sure it's a directory
196 if not os.path.isdir(name):
197 continue
198 # and has a wx subdir
199 if not os.path.exists(os.path.join(name, 'wx')):
200 continue
201 installed.append(_wxPackageInfo(name, True))
202
203 if removeExisting:
204 for rem in toRemove:
205 del sys.path[sys.path.index(rem)]
206
207 installed.sort()
208 installed.reverse()
209 return installed
210
211
212 class _wxPackageInfo(object):
213 def __init__(self, pathname, stripFirst=False):
214 self.pathname = pathname
215 base = os.path.basename(pathname)
216 segments = base.split('-')
217 if stripFirst:
218 segments = segments[1:]
219 self.version = tuple([int(x) for x in segments[0].split('.')])
220 self.options = segments[1:]
221
222
223 def Score(self, other):
224 score = 0
225
226 # whatever number of version components given in other must
227 # match exactly
228 minlen = min(len(self.version), len(other.version))
229 if self.version[:minlen] != other.version[:minlen]:
230 return 0
231 score += 1
232
233 for opt in other.options:
234 if opt in self.options:
235 score += 1
236 return score
237
238
239 # TODO: factor self.options into the sort order?
240 def __lt__(self, other):
241 return self.version < other.version
242 def __gt__(self, other):
243 return self.version > other.version
244 def __eq__(self, other):
245 return self.version == other.version
246
247
248
249 #----------------------------------------------------------------------
250
251 if __name__ == '__main__':
252 import pprint
253 def test(version):
254 # setup
255 savepath = sys.path[:]
256
257 #test
258 select(version)
259 print "Asked for %s:\t got: %s" % (version, sys.path[0])
260 #pprint.pprint(sys.path)
261 #print
262
263 # reset
264 sys.path = savepath[:]
265 global _selected
266 _selected = None
267
268
269 # make some test dirs
270 names = ['wx-2.4',
271 'wx-2.5.2',
272 'wx-2.5.2.9-gtk2-unicode',
273 'wx-2.5.2.9-gtk-ansi',
274 'wx-2.5.1',
275 'wx-2.5.2.8-gtk2-unicode',
276 'wx-2.5.3']
277 for name in names:
278 d = os.path.join('/tmp', name)
279 os.mkdir(d)
280 os.mkdir(os.path.join(d, 'wx'))
281
282 # setup sys.path to see those dirs
283 sys.path.append('/tmp')
284
285
286 # now run some tests
287 pprint.pprint( getInstalled())
288 print checkInstalled("2.4")
289 print checkInstalled("2.5-unicode")
290 print checkInstalled("2.99-bogus")
291 test("2.4")
292 test("2.5")
293 test("2.5-gtk2")
294 test("2.5.2")
295 test("2.5-ansi")
296 test("2.5-unicode")
297
298 # There isn't a unicode match for this one, but it will give the best
299 # available 2.4. Should it give an error instead? I don't think so...
300 test("2.4-unicode")
301
302 # Try asking for multiple versions
303 test(["2.6", "2.5.3", "2.5.2-gtk2"])
304
305 try:
306 # expecting an error on this one
307 test("2.6")
308 except VersionError, e:
309 print "Asked for 2.6:\t got Exception:", e
310
311 # check for exception when incompatible versions are requested
312 try:
313 select("2.4")
314 select("2.5")
315 except VersionError, e:
316 print "Asked for incompatible versions, got Exception:", e
317
318 # cleanup
319 for name in names:
320 d = os.path.join('/tmp', name)
321 os.rmdir(os.path.join(d, 'wx'))
322 os.rmdir(d)
323
324