]> git.saurik.com Git - wxWidgets.git/blame - wxPython/wxversion/wxversion.py
add skipupload flag
[wxWidgets.git] / wxPython / wxversion / wxversion.py
CommitLineData
d48c1c64
RD
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"""
16If you have more than one version of wxPython installed this module
17allows your application to choose which version of wxPython will be
5029118c 18imported when it does 'import wx'. You use it like this::
d48c1c64
RD
19
20 import wxversion
5029118c
RD
21 wxversion.select('2.4')
22 import wx
23
24Or additional build options can also be selected, like this::
25
26 import wxversion
27 wxversion.select('2.5.3-unicode')
d48c1c64
RD
28 import wx
29
30Of course the default wxPython version can also be controlled by
31setting PYTHONPATH or by editing the wx.pth path configuration file,
32but using wxversion will allow an application to manage the version
33selection itself rather than depend on the user to setup the
34environment correctly.
35
36It works by searching the sys.path for directories matching wx-* and
54c73383 37then comparing them to what was passed to the select function. If a
d48c1c64 38match is found then that path is inserted into sys.path.
5029118c
RD
39
40NOTE: If you are making a 'bundle' of your application with a tool
41like py2exe then you should *not* use the wxversion module since it
54c73383
RD
42looks at the filesystem for the directories on sys.path, it will fail
43in a bundled environment. Instead you should simply ensure that the
5029118c
RD
44version of wxPython that you want is found by default on the sys.path
45when making the bundled version by setting PYTHONPATH. Then that
46version will be included in your bundle and your app will work as
47expected. Py2exe and the others usually have a way to tell at runtime
48if they are running from a bundle or running raw, so you can check
49that 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
0148e434
RD
56More documentation on wxversion and multi-version installs can be
57found at: http://wiki.wxpython.org/index.cgi/MultiVersionInstalls
58
d48c1c64
RD
59"""
60
61import sys, os, glob, fnmatch
62
63
4f60dce5 64_selected = None
5029118c 65class VersionError(Exception):
4f60dce5 66 pass
d48c1c64 67
5029118c 68#----------------------------------------------------------------------
d48c1c64 69
5029118c 70def select(versions):
d48c1c64 71 """
5029118c
RD
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.
d48c1c64 77
93ba536a
RD
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.
d48c1c64
RD
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 """
d48c1c64
RD
96 if type(versions) == str:
97 versions = [versions]
4f60dce5
RD
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
5029118c 107 raise VersionError("A previously selected wx version does not match the new request.")
4f60dce5 108
0148e434
RD
109 # If we get here then this is the first time wxversion is used,
110 # ensure that wxPython hasn't been imported yet.
4f60dce5 111 if sys.modules.has_key('wx') or sys.modules.has_key('wxPython'):
54c73383
RD
112 raise VersionError("wxversion.select() must be called before wxPython is imported")
113
4f60dce5
RD
114 # Look for a matching version and manipulate the sys.path as
115 # needed to allow it to be imported.
54c73383
RD
116 installed = _find_installed(True)
117 bestMatch = _get_best_match(installed, versions)
5029118c
RD
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
6be3fd57
RD
127
128def ensureMinimal(minVersion):
54c73383 129 """
6be3fd57
RD
130 Checks to see if the default version of wxPython is greater-than
131 or equal to `minVersion`. If not then it will try to find an
132 installed version that is >= minVersion. If none are available
133 then a message is displayed that will inform the user and will
134 offer to open their web browser to the wxPython downloads page,
135 and will then exit the application.
54c73383
RD
136 """
137 assert type(minVersion) == str
138
139 # ensure that wxPython hasn't been imported yet.
140 if sys.modules.has_key('wx') or sys.modules.has_key('wxPython'):
6be3fd57
RD
141 raise VersionError("wxversion.ensureMinimal() must be called before wxPython is imported")
142
54c73383 143 bestMatch = None
54c73383 144 minv = _wxPackageInfo(minVersion)
6be3fd57
RD
145 defaultPath = _find_default()
146 if defaultPath:
147 defv = _wxPackageInfo(defaultPath, True)
148 if defv >= minv:
149 bestMatch = defv
54c73383 150
6be3fd57
RD
151 if bestMatch is None:
152 installed = _find_installed()
153 if installed:
154 # The list is in reverse sorted order, so if the first one is
155 # big enough then choose it
156 if installed[0] >= minv:
157 bestMatch = installed[0]
54c73383
RD
158
159 if bestMatch is None:
160 import wx, webbrowser
161 versions = "\n".join([" "+ver for ver in getInstalled()])
162 app = wx.PySimpleApp()
6be3fd57
RD
163 result = wx.MessageBox("This application requires a version of wxPython "
164 "greater than or equal to %s, but a matching version "
165 "was not found.\n\n"
166 "You currently have these version(s) installed:\n%s\n\n"
167 "Would you like to download a new version of wxPython?\n"
168 % (minVersion, versions),
169 "wxPython Upgrade Needed", style=wx.YES_NO)
170 if result == wx.YES:
171 webbrowser.open("http://sourceforge.net/project/showfiles.php?group_id=10718")
54c73383 172 app.MainLoop()
54c73383
RD
173 sys.exit()
174
175 sys.path.insert(0, bestMatch.pathname)
176 _selected = bestMatch
177
178
179#----------------------------------------------------------------------
180
5029118c
RD
181def checkInstalled(versions):
182 """
183 Check if there is a version of wxPython installed that matches one
184 of the versions given. Returns True if so, False if not. This
185 can be used to determine if calling `select` will succeed or not.
186
187 :param version: Same as in `select`, either a string or a list
188 of strings specifying the version(s) to check
189 for.
190 """
191
192 if type(versions) == str:
193 versions = [versions]
54c73383
RD
194 installed = _find_installed()
195 bestMatch = _get_best_match(installed, versions)
5029118c
RD
196 return bestMatch is not None
197
198#----------------------------------------------------------------------
199
200def getInstalled():
201 """
202 Returns a list of strings representing the installed wxPython
203 versions that are found on the system.
204 """
54c73383
RD
205 installed = _find_installed()
206 return [os.path.basename(p.pathname)[3:] for p in installed]
5029118c
RD
207
208
209
210#----------------------------------------------------------------------
211# private helpers...
212
54c73383 213def _get_best_match(installed, versions):
5029118c
RD
214 bestMatch = None
215 bestScore = 0
54c73383 216 for pkg in installed:
d48c1c64
RD
217 for ver in versions:
218 score = pkg.Score(_wxPackageInfo(ver))
219 if score > bestScore:
220 bestMatch = pkg
221 bestScore = score
5029118c 222 return bestMatch
d48c1c64
RD
223
224
225_pattern = "wx-[0-9].*"
5029118c 226def _find_installed(removeExisting=False):
d48c1c64 227 installed = []
17f3e530 228 toRemove = []
d48c1c64
RD
229 for pth in sys.path:
230
231 # empty means to look in the current dir
232 if not pth:
233 pth = '.'
234
235 # skip it if it's not a package dir
236 if not os.path.isdir(pth):
237 continue
238
239 base = os.path.basename(pth)
240
17f3e530
RD
241 # if it's a wx path that's already in the sys.path then mark
242 # it for removal and then skip it
d48c1c64 243 if fnmatch.fnmatchcase(base, _pattern):
17f3e530 244 toRemove.append(pth)
d48c1c64
RD
245 continue
246
247 # now look in the dir for matching subdirs
248 for name in glob.glob(os.path.join(pth, _pattern)):
249 # make sure it's a directory
250 if not os.path.isdir(name):
251 continue
252 # and has a wx subdir
253 if not os.path.exists(os.path.join(name, 'wx')):
254 continue
255 installed.append(_wxPackageInfo(name, True))
256
5029118c
RD
257 if removeExisting:
258 for rem in toRemove:
259 del sys.path[sys.path.index(rem)]
17f3e530 260
d48c1c64
RD
261 installed.sort()
262 installed.reverse()
263 return installed
264
265
6be3fd57
RD
266# Scan the sys.path looking for either a directory matching _pattern,
267# or a wx.pth file
268def _find_default():
269 for pth in sys.path:
270 # empty means to look in the current dir
271 if not pth:
272 pth = '.'
273
274 # skip it if it's not a package dir
275 if not os.path.isdir(pth):
276 continue
277
278 # does it match the pattern?
279 base = os.path.basename(pth)
280 if fnmatch.fnmatchcase(base, _pattern):
281 return pth
282
283 for pth in sys.path:
284 if not pth:
285 pth = '.'
286 if not os.path.isdir(pth):
287 continue
288 if os.path.exists(os.path.join(pth, 'wx.pth')):
289 base = open(os.path.join(pth, 'wx.pth')).read()
290 return os.path.join(pth, base)
291
292 return None
293
294
d48c1c64
RD
295class _wxPackageInfo(object):
296 def __init__(self, pathname, stripFirst=False):
297 self.pathname = pathname
298 base = os.path.basename(pathname)
299 segments = base.split('-')
300 if stripFirst:
301 segments = segments[1:]
302 self.version = tuple([int(x) for x in segments[0].split('.')])
303 self.options = segments[1:]
304
305
306 def Score(self, other):
307 score = 0
5029118c 308
0148e434
RD
309 # whatever number of version components given in other must
310 # match exactly
5029118c
RD
311 minlen = min(len(self.version), len(other.version))
312 if self.version[:minlen] != other.version[:minlen]:
313 return 0
0148e434 314 score += 1
5029118c 315
d48c1c64
RD
316 for opt in other.options:
317 if opt in self.options:
318 score += 1
319 return score
320
321
54c73383 322
d48c1c64 323 def __lt__(self, other):
54c73383
RD
324 return self.version < other.version or \
325 (self.version == other.version and self.options < other.options)
326 def __le__(self, other):
327 return self.version <= other.version or \
328 (self.version == other.version and self.options <= other.options)
329
d48c1c64 330 def __gt__(self, other):
54c73383
RD
331 return self.version > other.version or \
332 (self.version == other.version and self.options > other.options)
333 def __ge__(self, other):
334 return self.version >= other.version or \
335 (self.version == other.version and self.options >= other.options)
336
d48c1c64 337 def __eq__(self, other):
54c73383 338 return self.version == other.version and self.options == other.options
d48c1c64
RD
339
340
341
5029118c 342#----------------------------------------------------------------------
d48c1c64
RD
343
344if __name__ == '__main__':
17f3e530 345 import pprint
6be3fd57
RD
346
347 #ensureMinimal('2.5')
348 #pprint.pprint(sys.path)
54c73383
RD
349 #sys.exit()
350
351
d48c1c64 352 def test(version):
4f60dce5 353 # setup
d48c1c64 354 savepath = sys.path[:]
4f60dce5
RD
355
356 #test
5029118c 357 select(version)
d48c1c64 358 print "Asked for %s:\t got: %s" % (version, sys.path[0])
6be3fd57
RD
359 pprint.pprint(sys.path)
360 print
4f60dce5
RD
361
362 # reset
d48c1c64 363 sys.path = savepath[:]
4f60dce5
RD
364 global _selected
365 _selected = None
d48c1c64
RD
366
367
368 # make some test dirs
369 names = ['wx-2.4',
370 'wx-2.5.2',
371 'wx-2.5.2.9-gtk2-unicode',
372 'wx-2.5.2.9-gtk-ansi',
373 'wx-2.5.1',
374 'wx-2.5.2.8-gtk2-unicode',
375 'wx-2.5.3']
376 for name in names:
377 d = os.path.join('/tmp', name)
378 os.mkdir(d)
379 os.mkdir(os.path.join(d, 'wx'))
380
381 # setup sys.path to see those dirs
382 sys.path.append('/tmp')
383
384
385 # now run some tests
5029118c
RD
386 pprint.pprint( getInstalled())
387 print checkInstalled("2.4")
388 print checkInstalled("2.5-unicode")
389 print checkInstalled("2.99-bogus")
6be3fd57
RD
390 print "Current sys.path:"
391 pprint.pprint(sys.path)
392 print
393
d48c1c64
RD
394 test("2.4")
395 test("2.5")
396 test("2.5-gtk2")
397 test("2.5.2")
398 test("2.5-ansi")
399 test("2.5-unicode")
400
401 # There isn't a unicode match for this one, but it will give the best
402 # available 2.4. Should it give an error instead? I don't think so...
403 test("2.4-unicode")
404
4f60dce5
RD
405 # Try asking for multiple versions
406 test(["2.6", "2.5.3", "2.5.2-gtk2"])
407
d48c1c64
RD
408 try:
409 # expecting an error on this one
410 test("2.6")
5029118c 411 except VersionError, e:
4f60dce5 412 print "Asked for 2.6:\t got Exception:", e
d48c1c64 413
4f60dce5
RD
414 # check for exception when incompatible versions are requested
415 try:
5029118c
RD
416 select("2.4")
417 select("2.5")
418 except VersionError, e:
4f60dce5 419 print "Asked for incompatible versions, got Exception:", e
d48c1c64
RD
420
421 # cleanup
422 for name in names:
423 d = os.path.join('/tmp', name)
424 os.rmdir(os.path.join(d, 'wx'))
425 os.rmdir(d)
426
427