]> git.saurik.com Git - wxWidgets.git/blob - wxPython/wxversion/wxversion.py
Use a working dir for the uninstaller that does exist.
[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.require('2.4')
22 import wx
23
24 Of course the default wxPython version can also be controlled by
25 setting PYTHONPATH or by editing the wx.pth path configuration file,
26 but using wxversion will allow an application to manage the version
27 selection itself rather than depend on the user to setup the
28 environment correctly.
29
30 It works by searching the sys.path for directories matching wx-* and
31 then comparing them to what was passed to the require function. If a
32 match is found then that path is inserted into sys.path.
33 """
34
35 import sys, os, glob, fnmatch
36
37
38 _selected = None
39 class wxversionError(Exception):
40 pass
41
42
43 def require(versions):
44 """
45 Search for a wxPython installation that matches version.
46
47 :param version: Specifies the version to look for, it can
48 either be a string or a list of strings. Each
49 string is compared to the installed wxPythons
50 and the best match is inserted into the
51 sys.path, allowing an 'import wx' to find that
52 version.
53
54 The version string is composed of the dotted
55 version number (at least 2 of the 4 components)
56 optionally followed by hyphen ('-') separated
57 options (wx port, unicode/ansi, flavour, etc.) A
58 match is determined by how much of the installed
59 version matches what is given in the version
60 parameter. If the version number components don't
61 match then the score is zero, otherwise the score
62 is increased for every specified optional component
63 that is specified and that matches.
64 """
65 bestMatch = None
66 bestScore = 0
67 if type(versions) == str:
68 versions = [versions]
69
70 global _selected
71 if _selected is not None:
72 # A version was previously selected, ensure that it matches
73 # this new request
74 for ver in versions:
75 if _selected.Score(_wxPackageInfo(ver)) > 0:
76 return
77 # otherwise, raise an exception
78 raise wxversionError("A previously selected wx version does not match the new request.")
79
80 # If we get here then this is the first time wxversion is used.
81 # Ensure that wxPython hasn't been imported yet.
82 if sys.modules.has_key('wx') or sys.modules.has_key('wxPython'):
83 raise wxversionError("wxversion.require() must be called before wxPython is imported")
84
85 # Look for a matching version and manipulate the sys.path as
86 # needed to allow it to be imported.
87 packages = _find_installed()
88 for pkg in packages:
89 for ver in versions:
90 score = pkg.Score(_wxPackageInfo(ver))
91 if score > bestScore:
92 bestMatch = pkg
93 bestScore = score
94
95 if bestMatch is None:
96 raise wxversionError("Requested version of wxPython not found")
97
98 sys.path.insert(0, bestMatch.pathname)
99 _selected = bestMatch
100
101
102
103 _pattern = "wx-[0-9].*"
104 def _find_installed():
105 installed = []
106 toRemove = []
107 for pth in sys.path:
108
109 # empty means to look in the current dir
110 if not pth:
111 pth = '.'
112
113 # skip it if it's not a package dir
114 if not os.path.isdir(pth):
115 continue
116
117 base = os.path.basename(pth)
118
119 # if it's a wx path that's already in the sys.path then mark
120 # it for removal and then skip it
121 if fnmatch.fnmatchcase(base, _pattern):
122 toRemove.append(pth)
123 continue
124
125 # now look in the dir for matching subdirs
126 for name in glob.glob(os.path.join(pth, _pattern)):
127 # make sure it's a directory
128 if not os.path.isdir(name):
129 continue
130 # and has a wx subdir
131 if not os.path.exists(os.path.join(name, 'wx')):
132 continue
133 installed.append(_wxPackageInfo(name, True))
134
135 for rem in toRemove:
136 del sys.path[sys.path.index(rem)]
137
138 installed.sort()
139 installed.reverse()
140 return installed
141
142
143 class _wxPackageInfo(object):
144 def __init__(self, pathname, stripFirst=False):
145 self.pathname = pathname
146 base = os.path.basename(pathname)
147 segments = base.split('-')
148 if stripFirst:
149 segments = segments[1:]
150 self.version = tuple([int(x) for x in segments[0].split('.')])
151 self.options = segments[1:]
152
153
154 def Score(self, other):
155 score = 0
156 # whatever version components given in other must match exactly
157 if len(self.version) > len(other.version):
158 v = self.version[:len(other.version)]
159 else:
160 v = self.version
161 if v != other.version:
162 return 0
163 score += 1
164 for opt in other.options:
165 if opt in self.options:
166 score += 1
167 return score
168
169
170 # TODO: factor self.options into the sort order?
171 def __lt__(self, other):
172 return self.version < other.version
173 def __gt__(self, other):
174 return self.version > other.version
175 def __eq__(self, other):
176 return self.version == other.version
177
178
179
180
181
182 if __name__ == '__main__':
183 import pprint
184 def test(version):
185 # setup
186 savepath = sys.path[:]
187
188 #test
189 require(version)
190 print "Asked for %s:\t got: %s" % (version, sys.path[0])
191 #pprint.pprint(sys.path)
192 #print
193
194 # reset
195 sys.path = savepath[:]
196 global _selected
197 _selected = None
198
199
200 # make some test dirs
201 names = ['wx-2.4',
202 'wx-2.5.2',
203 'wx-2.5.2.9-gtk2-unicode',
204 'wx-2.5.2.9-gtk-ansi',
205 'wx-2.5.1',
206 'wx-2.5.2.8-gtk2-unicode',
207 'wx-2.5.3']
208 for name in names:
209 d = os.path.join('/tmp', name)
210 os.mkdir(d)
211 os.mkdir(os.path.join(d, 'wx'))
212
213 # setup sys.path to see those dirs
214 sys.path.append('/tmp')
215
216
217 # now run some tests
218 test("2.4")
219 test("2.5")
220 test("2.5-gtk2")
221 test("2.5.2")
222 test("2.5-ansi")
223 test("2.5-unicode")
224
225 # There isn't a unicode match for this one, but it will give the best
226 # available 2.4. Should it give an error instead? I don't think so...
227 test("2.4-unicode")
228
229 # Try asking for multiple versions
230 test(["2.6", "2.5.3", "2.5.2-gtk2"])
231
232 try:
233 # expecting an error on this one
234 test("2.6")
235 except wxversionError, e:
236 print "Asked for 2.6:\t got Exception:", e
237
238 # check for exception when incompatible versions are requested
239 try:
240 require("2.4")
241 require("2.5")
242 except wxversionError, e:
243 print "Asked for incompatible versions, got Exception:", e
244
245 # cleanup
246 for name in names:
247 d = os.path.join('/tmp', name)
248 os.rmdir(os.path.join(d, 'wx'))
249 os.rmdir(d)
250
251