3
|
1 |
"""Append module search paths for third-party packages to sys.path.
|
|
2 |
|
|
3 |
****************************************************************
|
|
4 |
* This module is automatically imported during initialization. *
|
|
5 |
****************************************************************
|
|
6 |
|
|
7 |
In earlier versions of Python (up to 1.5a3), scripts or modules that
|
|
8 |
needed to use site-specific modules would place ``import site''
|
|
9 |
somewhere near the top of their code. Because of the automatic
|
|
10 |
import, this is no longer necessary (but code that does it still
|
|
11 |
works).
|
|
12 |
|
|
13 |
This will append site-specific paths to the module search path. On
|
|
14 |
Unix, it starts with sys.prefix and sys.exec_prefix (if different) and
|
|
15 |
appends lib/python<version>/site-packages as well as lib/site-python.
|
|
16 |
It also supports the Debian convention of
|
|
17 |
lib/python<version>/dist-packages. On other platforms (mainly Mac and
|
|
18 |
Windows), it uses just sys.prefix (and sys.exec_prefix, if different,
|
|
19 |
but this is unlikely). The resulting directories, if they exist, are
|
|
20 |
appended to sys.path, and also inspected for path configuration files.
|
|
21 |
|
|
22 |
FOR DEBIAN, this sys.path is augmented with directories in /usr/local.
|
|
23 |
Local addons go into /usr/local/lib/python<version>/site-packages
|
|
24 |
(resp. /usr/local/lib/site-python), Debian addons install into
|
|
25 |
/usr/{lib,share}/python<version>/dist-packages.
|
|
26 |
|
|
27 |
A path configuration file is a file whose name has the form
|
|
28 |
<package>.pth; its contents are additional directories (one per line)
|
|
29 |
to be added to sys.path. Non-existing directories (or
|
|
30 |
non-directories) are never added to sys.path; no directory is added to
|
|
31 |
sys.path more than once. Blank lines and lines beginning with
|
|
32 |
'#' are skipped. Lines starting with 'import' are executed.
|
|
33 |
|
|
34 |
For example, suppose sys.prefix and sys.exec_prefix are set to
|
|
35 |
/usr/local and there is a directory /usr/local/lib/python2.X/site-packages
|
|
36 |
with three subdirectories, foo, bar and spam, and two path
|
|
37 |
configuration files, foo.pth and bar.pth. Assume foo.pth contains the
|
|
38 |
following:
|
|
39 |
|
|
40 |
# foo package configuration
|
|
41 |
foo
|
|
42 |
bar
|
|
43 |
bletch
|
|
44 |
|
|
45 |
and bar.pth contains:
|
|
46 |
|
|
47 |
# bar package configuration
|
|
48 |
bar
|
|
49 |
|
|
50 |
Then the following directories are added to sys.path, in this order:
|
|
51 |
|
|
52 |
/usr/local/lib/python2.X/site-packages/bar
|
|
53 |
/usr/local/lib/python2.X/site-packages/foo
|
|
54 |
|
|
55 |
Note that bletch is omitted because it doesn't exist; bar precedes foo
|
|
56 |
because bar.pth comes alphabetically before foo.pth; and spam is
|
|
57 |
omitted because it is not mentioned in either path configuration file.
|
|
58 |
|
|
59 |
After these path manipulations, an attempt is made to import a module
|
|
60 |
named sitecustomize, which can perform arbitrary additional
|
|
61 |
site-specific customizations. If this import fails with an
|
|
62 |
ImportError exception, it is silently ignored.
|
|
63 |
|
|
64 |
"""
|
|
65 |
|
|
66 |
import sys
|
|
67 |
import os
|
|
68 |
import __builtin__
|
|
69 |
try:
|
|
70 |
set
|
|
71 |
except NameError:
|
|
72 |
from sets import Set as set
|
|
73 |
|
|
74 |
# Prefixes for site-packages; add additional prefixes like /usr/local here
|
|
75 |
PREFIXES = [sys.prefix, sys.exec_prefix]
|
|
76 |
# Enable per user site-packages directory
|
|
77 |
# set it to False to disable the feature or True to force the feature
|
|
78 |
ENABLE_USER_SITE = None
|
|
79 |
# for distutils.commands.install
|
|
80 |
USER_SITE = None
|
|
81 |
USER_BASE = None
|
|
82 |
|
|
83 |
_is_jython = sys.platform[:4] == 'java'
|
|
84 |
|
|
85 |
def makepath(*paths):
|
|
86 |
dir = os.path.join(*paths)
|
|
87 |
if _is_jython and (dir == '__classpath__' or
|
|
88 |
dir.startswith('__pyclasspath__')):
|
|
89 |
return dir, dir
|
|
90 |
dir = os.path.abspath(dir)
|
|
91 |
return dir, os.path.normcase(dir)
|
|
92 |
|
|
93 |
def abs__file__():
|
|
94 |
"""Set all module' __file__ attribute to an absolute path"""
|
|
95 |
for m in sys.modules.values():
|
|
96 |
f = getattr(m, '__file__', None)
|
|
97 |
if f is None:
|
|
98 |
continue
|
|
99 |
m.__file__ = os.path.abspath(f)
|
|
100 |
|
|
101 |
def removeduppaths():
|
|
102 |
""" Remove duplicate entries from sys.path along with making them
|
|
103 |
absolute"""
|
|
104 |
# This ensures that the initial path provided by the interpreter contains
|
|
105 |
# only absolute pathnames, even if we're running from the build directory.
|
|
106 |
L = []
|
|
107 |
known_paths = set()
|
|
108 |
for dir in sys.path:
|
|
109 |
# Filter out duplicate paths (on case-insensitive file systems also
|
|
110 |
# if they only differ in case); turn relative paths into absolute
|
|
111 |
# paths.
|
|
112 |
dir, dircase = makepath(dir)
|
|
113 |
if not dircase in known_paths:
|
|
114 |
L.append(dir)
|
|
115 |
known_paths.add(dircase)
|
|
116 |
sys.path[:] = L
|
|
117 |
return known_paths
|
|
118 |
|
|
119 |
# XXX This should not be part of site.py, since it is needed even when
|
|
120 |
# using the -S option for Python. See http://www.python.org/sf/586680
|
|
121 |
def addbuilddir():
|
|
122 |
"""Append ./build/lib.<platform> in case we're running in the build dir
|
|
123 |
(especially for Guido :-)"""
|
|
124 |
from distutils.util import get_platform
|
|
125 |
s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
|
|
126 |
if hasattr(sys, 'gettotalrefcount'):
|
|
127 |
s += '-pydebug'
|
|
128 |
s = os.path.join(os.path.dirname(sys.path[-1]), s)
|
|
129 |
sys.path.append(s)
|
|
130 |
|
|
131 |
def _init_pathinfo():
|
|
132 |
"""Return a set containing all existing directory entries from sys.path"""
|
|
133 |
d = set()
|
|
134 |
for dir in sys.path:
|
|
135 |
try:
|
|
136 |
if os.path.isdir(dir):
|
|
137 |
dir, dircase = makepath(dir)
|
|
138 |
d.add(dircase)
|
|
139 |
except TypeError:
|
|
140 |
continue
|
|
141 |
return d
|
|
142 |
|
|
143 |
def addpackage(sitedir, name, known_paths):
|
|
144 |
"""Add a new path to known_paths by combining sitedir and 'name' or execute
|
|
145 |
sitedir if it starts with 'import'"""
|
|
146 |
if known_paths is None:
|
|
147 |
_init_pathinfo()
|
|
148 |
reset = 1
|
|
149 |
else:
|
|
150 |
reset = 0
|
|
151 |
fullname = os.path.join(sitedir, name)
|
|
152 |
try:
|
|
153 |
f = open(fullname, "rU")
|
|
154 |
except IOError:
|
|
155 |
return
|
|
156 |
try:
|
|
157 |
for line in f:
|
|
158 |
if line.startswith("#"):
|
|
159 |
continue
|
|
160 |
if line.startswith("import"):
|
|
161 |
exec line
|
|
162 |
continue
|
|
163 |
line = line.rstrip()
|
|
164 |
dir, dircase = makepath(sitedir, line)
|
|
165 |
if not dircase in known_paths and os.path.exists(dir):
|
|
166 |
sys.path.append(dir)
|
|
167 |
known_paths.add(dircase)
|
|
168 |
finally:
|
|
169 |
f.close()
|
|
170 |
if reset:
|
|
171 |
known_paths = None
|
|
172 |
return known_paths
|
|
173 |
|
|
174 |
def addsitedir(sitedir, known_paths=None):
|
|
175 |
"""Add 'sitedir' argument to sys.path if missing and handle .pth files in
|
|
176 |
'sitedir'"""
|
|
177 |
if known_paths is None:
|
|
178 |
known_paths = _init_pathinfo()
|
|
179 |
reset = 1
|
|
180 |
else:
|
|
181 |
reset = 0
|
|
182 |
sitedir, sitedircase = makepath(sitedir)
|
|
183 |
if not sitedircase in known_paths:
|
|
184 |
sys.path.append(sitedir) # Add path component
|
|
185 |
try:
|
|
186 |
names = os.listdir(sitedir)
|
|
187 |
except os.error:
|
|
188 |
return
|
|
189 |
names.sort()
|
|
190 |
for name in names:
|
|
191 |
if name.endswith(os.extsep + "pth"):
|
|
192 |
addpackage(sitedir, name, known_paths)
|
|
193 |
if reset:
|
|
194 |
known_paths = None
|
|
195 |
return known_paths
|
|
196 |
|
|
197 |
def addsitepackages(known_paths, sys_prefix=sys.prefix, exec_prefix=sys.exec_prefix):
|
|
198 |
"""Add site-packages (and possibly site-python) to sys.path"""
|
|
199 |
prefixes = [os.path.join(sys_prefix, "local"), sys_prefix]
|
|
200 |
if exec_prefix != sys_prefix:
|
|
201 |
prefixes.append(os.path.join(exec_prefix, "local"))
|
|
202 |
|
|
203 |
for prefix in prefixes:
|
|
204 |
if prefix:
|
|
205 |
if sys.platform in ('os2emx', 'riscos') or _is_jython:
|
|
206 |
sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
|
|
207 |
elif sys.platform == 'darwin' and prefix == sys_prefix:
|
|
208 |
|
|
209 |
if prefix.startswith("/System/Library/Frameworks/"): # Apple's Python
|
|
210 |
|
|
211 |
sitedirs = [os.path.join("/Library/Python", sys.version[:3], "site-packages"),
|
|
212 |
os.path.join(prefix, "Extras", "lib", "python")]
|
|
213 |
|
|
214 |
else: # any other Python distros on OSX work this way
|
|
215 |
sitedirs = [os.path.join(prefix, "lib",
|
|
216 |
"python" + sys.version[:3], "site-packages")]
|
|
217 |
|
|
218 |
elif os.sep == '/':
|
|
219 |
sitedirs = [os.path.join(prefix,
|
|
220 |
"lib",
|
|
221 |
"python" + sys.version[:3],
|
|
222 |
"site-packages"),
|
|
223 |
os.path.join(prefix, "lib", "site-python"),
|
|
224 |
os.path.join(prefix, "python" + sys.version[:3], "lib-dynload")]
|
|
225 |
lib64_dir = os.path.join(prefix, "lib64", "python" + sys.version[:3], "site-packages")
|
|
226 |
if (os.path.exists(lib64_dir) and
|
|
227 |
os.path.realpath(lib64_dir) not in [os.path.realpath(p) for p in sitedirs]):
|
|
228 |
sitedirs.append(lib64_dir)
|
|
229 |
try:
|
|
230 |
# sys.getobjects only available in --with-pydebug build
|
|
231 |
sys.getobjects
|
|
232 |
sitedirs.insert(0, os.path.join(sitedirs[0], 'debug'))
|
|
233 |
except AttributeError:
|
|
234 |
pass
|
|
235 |
# Debian-specific dist-packages directories:
|
|
236 |
sitedirs.append(os.path.join(prefix, "lib",
|
|
237 |
"python" + sys.version[:3],
|
|
238 |
"dist-packages"))
|
|
239 |
sitedirs.append(os.path.join(prefix, "local/lib",
|
|
240 |
"python" + sys.version[:3],
|
|
241 |
"dist-packages"))
|
|
242 |
sitedirs.append(os.path.join(prefix, "lib", "dist-python"))
|
|
243 |
else:
|
|
244 |
sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
|
|
245 |
if sys.platform == 'darwin':
|
|
246 |
# for framework builds *only* we add the standard Apple
|
|
247 |
# locations. Currently only per-user, but /Library and
|
|
248 |
# /Network/Library could be added too
|
|
249 |
if 'Python.framework' in prefix:
|
|
250 |
home = os.environ.get('HOME')
|
|
251 |
if home:
|
|
252 |
sitedirs.append(
|
|
253 |
os.path.join(home,
|
|
254 |
'Library',
|
|
255 |
'Python',
|
|
256 |
sys.version[:3],
|
|
257 |
'site-packages'))
|
|
258 |
for sitedir in sitedirs:
|
|
259 |
if os.path.isdir(sitedir):
|
|
260 |
addsitedir(sitedir, known_paths)
|
|
261 |
return None
|
|
262 |
|
|
263 |
def check_enableusersite():
|
|
264 |
"""Check if user site directory is safe for inclusion
|
|
265 |
|
|
266 |
The function tests for the command line flag (including environment var),
|
|
267 |
process uid/gid equal to effective uid/gid.
|
|
268 |
|
|
269 |
None: Disabled for security reasons
|
|
270 |
False: Disabled by user (command line option)
|
|
271 |
True: Safe and enabled
|
|
272 |
"""
|
|
273 |
if hasattr(sys, 'flags') and getattr(sys.flags, 'no_user_site', False):
|
|
274 |
return False
|
|
275 |
|
|
276 |
if hasattr(os, "getuid") and hasattr(os, "geteuid"):
|
|
277 |
# check process uid == effective uid
|
|
278 |
if os.geteuid() != os.getuid():
|
|
279 |
return None
|
|
280 |
if hasattr(os, "getgid") and hasattr(os, "getegid"):
|
|
281 |
# check process gid == effective gid
|
|
282 |
if os.getegid() != os.getgid():
|
|
283 |
return None
|
|
284 |
|
|
285 |
return True
|
|
286 |
|
|
287 |
def addusersitepackages(known_paths):
|
|
288 |
"""Add a per user site-package to sys.path
|
|
289 |
|
|
290 |
Each user has its own python directory with site-packages in the
|
|
291 |
home directory.
|
|
292 |
|
|
293 |
USER_BASE is the root directory for all Python versions
|
|
294 |
|
|
295 |
USER_SITE is the user specific site-packages directory
|
|
296 |
|
|
297 |
USER_SITE/.. can be used for data.
|
|
298 |
"""
|
|
299 |
global USER_BASE, USER_SITE, ENABLE_USER_SITE
|
|
300 |
env_base = os.environ.get("PYTHONUSERBASE", None)
|
|
301 |
|
|
302 |
def joinuser(*args):
|
|
303 |
return os.path.expanduser(os.path.join(*args))
|
|
304 |
|
|
305 |
#if sys.platform in ('os2emx', 'riscos'):
|
|
306 |
# # Don't know what to put here
|
|
307 |
# USER_BASE = ''
|
|
308 |
# USER_SITE = ''
|
|
309 |
if os.name == "nt":
|
|
310 |
base = os.environ.get("APPDATA") or "~"
|
|
311 |
if env_base:
|
|
312 |
USER_BASE = env_base
|
|
313 |
else:
|
|
314 |
USER_BASE = joinuser(base, "Python")
|
|
315 |
USER_SITE = os.path.join(USER_BASE,
|
|
316 |
"Python" + sys.version[0] + sys.version[2],
|
|
317 |
"site-packages")
|
|
318 |
else:
|
|
319 |
if env_base:
|
|
320 |
USER_BASE = env_base
|
|
321 |
else:
|
|
322 |
USER_BASE = joinuser("~", ".local")
|
|
323 |
USER_SITE = os.path.join(USER_BASE, "lib",
|
|
324 |
"python" + sys.version[:3],
|
|
325 |
"site-packages")
|
|
326 |
|
|
327 |
if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
|
|
328 |
addsitedir(USER_SITE, known_paths)
|
|
329 |
if ENABLE_USER_SITE:
|
|
330 |
for dist_libdir in ("lib", "local/lib"):
|
|
331 |
user_site = os.path.join(USER_BASE, dist_libdir,
|
|
332 |
"python" + sys.version[:3],
|
|
333 |
"dist-packages")
|
|
334 |
if os.path.isdir(user_site):
|
|
335 |
addsitedir(user_site, known_paths)
|
|
336 |
return known_paths
|
|
337 |
|
|
338 |
|
|
339 |
|
|
340 |
def setBEGINLIBPATH():
|
|
341 |
"""The OS/2 EMX port has optional extension modules that do double duty
|
|
342 |
as DLLs (and must use the .DLL file extension) for other extensions.
|
|
343 |
The library search path needs to be amended so these will be found
|
|
344 |
during module import. Use BEGINLIBPATH so that these are at the start
|
|
345 |
of the library search path.
|
|
346 |
|
|
347 |
"""
|
|
348 |
dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
|
|
349 |
libpath = os.environ['BEGINLIBPATH'].split(';')
|
|
350 |
if libpath[-1]:
|
|
351 |
libpath.append(dllpath)
|
|
352 |
else:
|
|
353 |
libpath[-1] = dllpath
|
|
354 |
os.environ['BEGINLIBPATH'] = ';'.join(libpath)
|
|
355 |
|
|
356 |
|
|
357 |
def setquit():
|
|
358 |
"""Define new built-ins 'quit' and 'exit'.
|
|
359 |
These are simply strings that display a hint on how to exit.
|
|
360 |
|
|
361 |
"""
|
|
362 |
if os.sep == ':':
|
|
363 |
eof = 'Cmd-Q'
|
|
364 |
elif os.sep == '\\':
|
|
365 |
eof = 'Ctrl-Z plus Return'
|
|
366 |
else:
|
|
367 |
eof = 'Ctrl-D (i.e. EOF)'
|
|
368 |
|
|
369 |
class Quitter(object):
|
|
370 |
def __init__(self, name):
|
|
371 |
self.name = name
|
|
372 |
def __repr__(self):
|
|
373 |
return 'Use %s() or %s to exit' % (self.name, eof)
|
|
374 |
def __call__(self, code=None):
|
|
375 |
# Shells like IDLE catch the SystemExit, but listen when their
|
|
376 |
# stdin wrapper is closed.
|
|
377 |
try:
|
|
378 |
sys.stdin.close()
|
|
379 |
except:
|
|
380 |
pass
|
|
381 |
raise SystemExit(code)
|
|
382 |
__builtin__.quit = Quitter('quit')
|
|
383 |
__builtin__.exit = Quitter('exit')
|
|
384 |
|
|
385 |
|
|
386 |
class _Printer(object):
|
|
387 |
"""interactive prompt objects for printing the license text, a list of
|
|
388 |
contributors and the copyright notice."""
|
|
389 |
|
|
390 |
MAXLINES = 23
|
|
391 |
|
|
392 |
def __init__(self, name, data, files=(), dirs=()):
|
|
393 |
self.__name = name
|
|
394 |
self.__data = data
|
|
395 |
self.__files = files
|
|
396 |
self.__dirs = dirs
|
|
397 |
self.__lines = None
|
|
398 |
|
|
399 |
def __setup(self):
|
|
400 |
if self.__lines:
|
|
401 |
return
|
|
402 |
data = None
|
|
403 |
for dir in self.__dirs:
|
|
404 |
for filename in self.__files:
|
|
405 |
filename = os.path.join(dir, filename)
|
|
406 |
try:
|
|
407 |
fp = file(filename, "rU")
|
|
408 |
data = fp.read()
|
|
409 |
fp.close()
|
|
410 |
break
|
|
411 |
except IOError:
|
|
412 |
pass
|
|
413 |
if data:
|
|
414 |
break
|
|
415 |
if not data:
|
|
416 |
data = self.__data
|
|
417 |
self.__lines = data.split('\n')
|
|
418 |
self.__linecnt = len(self.__lines)
|
|
419 |
|
|
420 |
def __repr__(self):
|
|
421 |
self.__setup()
|
|
422 |
if len(self.__lines) <= self.MAXLINES:
|
|
423 |
return "\n".join(self.__lines)
|
|
424 |
else:
|
|
425 |
return "Type %s() to see the full %s text" % ((self.__name,)*2)
|
|
426 |
|
|
427 |
def __call__(self):
|
|
428 |
self.__setup()
|
|
429 |
prompt = 'Hit Return for more, or q (and Return) to quit: '
|
|
430 |
lineno = 0
|
|
431 |
while 1:
|
|
432 |
try:
|
|
433 |
for i in range(lineno, lineno + self.MAXLINES):
|
|
434 |
print self.__lines[i]
|
|
435 |
except IndexError:
|
|
436 |
break
|
|
437 |
else:
|
|
438 |
lineno += self.MAXLINES
|
|
439 |
key = None
|
|
440 |
while key is None:
|
|
441 |
key = raw_input(prompt)
|
|
442 |
if key not in ('', 'q'):
|
|
443 |
key = None
|
|
444 |
if key == 'q':
|
|
445 |
break
|
|
446 |
|
|
447 |
def setcopyright():
|
|
448 |
"""Set 'copyright' and 'credits' in __builtin__"""
|
|
449 |
__builtin__.copyright = _Printer("copyright", sys.copyright)
|
|
450 |
if _is_jython:
|
|
451 |
__builtin__.credits = _Printer(
|
|
452 |
"credits",
|
|
453 |
"Jython is maintained by the Jython developers (www.jython.org).")
|
|
454 |
else:
|
|
455 |
__builtin__.credits = _Printer("credits", """\
|
|
456 |
Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
|
|
457 |
for supporting Python development. See www.python.org for more information.""")
|
|
458 |
here = os.path.dirname(os.__file__)
|
|
459 |
__builtin__.license = _Printer(
|
|
460 |
"license", "See http://www.python.org/%.3s/license.html" % sys.version,
|
|
461 |
["LICENSE.txt", "LICENSE"],
|
|
462 |
[os.path.join(here, os.pardir), here, os.curdir])
|
|
463 |
|
|
464 |
|
|
465 |
class _Helper(object):
|
|
466 |
"""Define the built-in 'help'.
|
|
467 |
This is a wrapper around pydoc.help (with a twist).
|
|
468 |
|
|
469 |
"""
|
|
470 |
|
|
471 |
def __repr__(self):
|
|
472 |
return "Type help() for interactive help, " \
|
|
473 |
"or help(object) for help about object."
|
|
474 |
def __call__(self, *args, **kwds):
|
|
475 |
import pydoc
|
|
476 |
return pydoc.help(*args, **kwds)
|
|
477 |
|
|
478 |
def sethelper():
|
|
479 |
__builtin__.help = _Helper()
|
|
480 |
|
|
481 |
def aliasmbcs():
|
|
482 |
"""On Windows, some default encodings are not provided by Python,
|
|
483 |
while they are always available as "mbcs" in each locale. Make
|
|
484 |
them usable by aliasing to "mbcs" in such a case."""
|
|
485 |
if sys.platform == 'win32':
|
|
486 |
import locale, codecs
|
|
487 |
enc = locale.getdefaultlocale()[1]
|
|
488 |
if enc.startswith('cp'): # "cp***" ?
|
|
489 |
try:
|
|
490 |
codecs.lookup(enc)
|
|
491 |
except LookupError:
|
|
492 |
import encodings
|
|
493 |
encodings._cache[enc] = encodings._unknown
|
|
494 |
encodings.aliases.aliases[enc] = 'mbcs'
|
|
495 |
|
|
496 |
def setencoding():
|
|
497 |
"""Set the string encoding used by the Unicode implementation. The
|
|
498 |
default is 'ascii', but if you're willing to experiment, you can
|
|
499 |
change this."""
|
|
500 |
encoding = "ascii" # Default value set by _PyUnicode_Init()
|
|
501 |
if 0:
|
|
502 |
# Enable to support locale aware default string encodings.
|
|
503 |
import locale
|
|
504 |
loc = locale.getdefaultlocale()
|
|
505 |
if loc[1]:
|
|
506 |
encoding = loc[1]
|
|
507 |
if 0:
|
|
508 |
# Enable to switch off string to Unicode coercion and implicit
|
|
509 |
# Unicode to string conversion.
|
|
510 |
encoding = "undefined"
|
|
511 |
if encoding != "ascii":
|
|
512 |
# On Non-Unicode builds this will raise an AttributeError...
|
|
513 |
sys.setdefaultencoding(encoding) # Needs Python Unicode build !
|
|
514 |
|
|
515 |
|
|
516 |
def execsitecustomize():
|
|
517 |
"""Run custom site specific code, if available."""
|
|
518 |
try:
|
|
519 |
import sitecustomize
|
|
520 |
except ImportError:
|
|
521 |
pass
|
|
522 |
|
|
523 |
def virtual_install_main_packages():
|
|
524 |
f = open(os.path.join(os.path.dirname(__file__), 'orig-prefix.txt'))
|
|
525 |
sys.real_prefix = f.read().strip()
|
|
526 |
f.close()
|
|
527 |
pos = 2
|
|
528 |
if sys.path[0] == '':
|
|
529 |
pos += 1
|
|
530 |
if sys.platform == 'win32':
|
|
531 |
paths = [os.path.join(sys.real_prefix, 'Lib'), os.path.join(sys.real_prefix, 'DLLs')]
|
|
532 |
elif _is_jython:
|
|
533 |
paths = [os.path.join(sys.real_prefix, 'Lib')]
|
|
534 |
else:
|
|
535 |
paths = [os.path.join(sys.real_prefix, 'lib', 'python'+sys.version[:3])]
|
|
536 |
lib64_path = os.path.join(sys.real_prefix, 'lib64', 'python'+sys.version[:3])
|
|
537 |
if os.path.exists(lib64_path):
|
|
538 |
paths.append(lib64_path)
|
|
539 |
# This is hardcoded in the Python executable, but relative to sys.prefix:
|
|
540 |
plat_path = os.path.join(sys.real_prefix, 'lib', 'python'+sys.version[:3],
|
|
541 |
'plat-%s' % sys.platform)
|
|
542 |
if os.path.exists(plat_path):
|
|
543 |
paths.append(plat_path)
|
|
544 |
# This is hardcoded in the Python executable, but
|
|
545 |
# relative to sys.prefix, so we have to fix up:
|
|
546 |
for path in list(paths):
|
|
547 |
tk_dir = os.path.join(path, 'lib-tk')
|
|
548 |
if os.path.exists(tk_dir):
|
|
549 |
paths.append(tk_dir)
|
|
550 |
|
|
551 |
# These are hardcoded in the Apple's Python executable,
|
|
552 |
# but relative to sys.prefix, so we have to fix them up:
|
|
553 |
if sys.platform == 'darwin':
|
|
554 |
hardcoded_paths = [os.path.join(sys.real_prefix, 'lib', 'python'+sys.version[:3], module)
|
|
555 |
for module in ('plat-darwin', 'plat-mac', 'plat-mac/lib-scriptpackages')]
|
|
556 |
|
|
557 |
for path in hardcoded_paths:
|
|
558 |
if os.path.exists(path):
|
|
559 |
paths.append(path)
|
|
560 |
|
|
561 |
sys.path.extend(paths)
|
|
562 |
|
|
563 |
def force_global_eggs_after_local_site_packages():
|
|
564 |
"""
|
|
565 |
Force easy_installed eggs in the global environment to get placed
|
|
566 |
in sys.path after all packages inside the virtualenv. This
|
|
567 |
maintains the "least surprise" result that packages in the
|
|
568 |
virtualenv always mask global packages, never the other way
|
|
569 |
around.
|
|
570 |
|
|
571 |
"""
|
|
572 |
egginsert = getattr(sys, '__egginsert', 0)
|
|
573 |
for i, path in enumerate(sys.path):
|
|
574 |
if i > egginsert and path.startswith(sys.prefix):
|
|
575 |
egginsert = i
|
|
576 |
sys.__egginsert = egginsert + 1
|
|
577 |
|
|
578 |
def virtual_addsitepackages(known_paths):
|
|
579 |
force_global_eggs_after_local_site_packages()
|
|
580 |
return addsitepackages(known_paths, sys_prefix=sys.real_prefix)
|
|
581 |
|
|
582 |
def fixclasspath():
|
|
583 |
"""Adjust the special classpath sys.path entries for Jython. These
|
|
584 |
entries should follow the base virtualenv lib directories.
|
|
585 |
"""
|
|
586 |
paths = []
|
|
587 |
classpaths = []
|
|
588 |
for path in sys.path:
|
|
589 |
if path == '__classpath__' or path.startswith('__pyclasspath__'):
|
|
590 |
classpaths.append(path)
|
|
591 |
else:
|
|
592 |
paths.append(path)
|
|
593 |
sys.path = paths
|
|
594 |
sys.path.extend(classpaths)
|
|
595 |
|
|
596 |
def execusercustomize():
|
|
597 |
"""Run custom user specific code, if available."""
|
|
598 |
try:
|
|
599 |
import usercustomize
|
|
600 |
except ImportError:
|
|
601 |
pass
|
|
602 |
|
|
603 |
|
|
604 |
def main():
|
|
605 |
global ENABLE_USER_SITE
|
|
606 |
virtual_install_main_packages()
|
|
607 |
abs__file__()
|
|
608 |
paths_in_sys = removeduppaths()
|
|
609 |
if (os.name == "posix" and sys.path and
|
|
610 |
os.path.basename(sys.path[-1]) == "Modules"):
|
|
611 |
addbuilddir()
|
|
612 |
if _is_jython:
|
|
613 |
fixclasspath()
|
|
614 |
GLOBAL_SITE_PACKAGES = not os.path.exists(os.path.join(os.path.dirname(__file__), 'no-global-site-packages.txt'))
|
|
615 |
if not GLOBAL_SITE_PACKAGES:
|
|
616 |
ENABLE_USER_SITE = False
|
|
617 |
if ENABLE_USER_SITE is None:
|
|
618 |
ENABLE_USER_SITE = check_enableusersite()
|
|
619 |
paths_in_sys = addsitepackages(paths_in_sys)
|
|
620 |
paths_in_sys = addusersitepackages(paths_in_sys)
|
|
621 |
if GLOBAL_SITE_PACKAGES:
|
|
622 |
paths_in_sys = virtual_addsitepackages(paths_in_sys)
|
|
623 |
if sys.platform == 'os2emx':
|
|
624 |
setBEGINLIBPATH()
|
|
625 |
setquit()
|
|
626 |
setcopyright()
|
|
627 |
sethelper()
|
|
628 |
aliasmbcs()
|
|
629 |
setencoding()
|
|
630 |
execsitecustomize()
|
|
631 |
if ENABLE_USER_SITE:
|
|
632 |
execusercustomize()
|
|
633 |
# Remove sys.setdefaultencoding() so that users cannot change the
|
|
634 |
# encoding after initialization. The test for presence is needed when
|
|
635 |
# this module is run as a script, because this code is executed twice.
|
|
636 |
if hasattr(sys, "setdefaultencoding"):
|
|
637 |
del sys.setdefaultencoding
|
|
638 |
|
|
639 |
main()
|
|
640 |
|
|
641 |
def _script():
|
|
642 |
help = """\
|
|
643 |
%s [--user-base] [--user-site]
|
|
644 |
|
|
645 |
Without arguments print some useful information
|
|
646 |
With arguments print the value of USER_BASE and/or USER_SITE separated
|
|
647 |
by '%s'.
|
|
648 |
|
|
649 |
Exit codes with --user-base or --user-site:
|
|
650 |
0 - user site directory is enabled
|
|
651 |
1 - user site directory is disabled by user
|
|
652 |
2 - uses site directory is disabled by super user
|
|
653 |
or for security reasons
|
|
654 |
>2 - unknown error
|
|
655 |
"""
|
|
656 |
args = sys.argv[1:]
|
|
657 |
if not args:
|
|
658 |
print "sys.path = ["
|
|
659 |
for dir in sys.path:
|
|
660 |
print " %r," % (dir,)
|
|
661 |
print "]"
|
|
662 |
def exists(path):
|
|
663 |
if os.path.isdir(path):
|
|
664 |
return "exists"
|
|
665 |
else:
|
|
666 |
return "doesn't exist"
|
|
667 |
print "USER_BASE: %r (%s)" % (USER_BASE, exists(USER_BASE))
|
|
668 |
print "USER_SITE: %r (%s)" % (USER_SITE, exists(USER_BASE))
|
|
669 |
print "ENABLE_USER_SITE: %r" % ENABLE_USER_SITE
|
|
670 |
sys.exit(0)
|
|
671 |
|
|
672 |
buffer = []
|
|
673 |
if '--user-base' in args:
|
|
674 |
buffer.append(USER_BASE)
|
|
675 |
if '--user-site' in args:
|
|
676 |
buffer.append(USER_SITE)
|
|
677 |
|
|
678 |
if buffer:
|
|
679 |
print os.pathsep.join(buffer)
|
|
680 |
if ENABLE_USER_SITE:
|
|
681 |
sys.exit(0)
|
|
682 |
elif ENABLE_USER_SITE is False:
|
|
683 |
sys.exit(1)
|
|
684 |
elif ENABLE_USER_SITE is None:
|
|
685 |
sys.exit(2)
|
|
686 |
else:
|
|
687 |
sys.exit(3)
|
|
688 |
else:
|
|
689 |
import textwrap
|
|
690 |
print textwrap.dedent(help % (sys.argv[0], os.pathsep))
|
|
691 |
sys.exit(10)
|
|
692 |
|
|
693 |
if __name__ == '__main__':
|
|
694 |
_script()
|