blob: 865fffb7b52970412f6ef5800919061fcae51b33 [file] [log] [blame]
Guido van Rossumf30bec71997-08-29 22:30:45 +00001"""Append module search paths for third-party packages to sys.path.
Guido van Rossume57c96e1996-08-17 19:56:26 +00002
Guido van Rossumf30bec71997-08-29 22:30:45 +00003****************************************************************
4* This module is automatically imported during initialization. *
5****************************************************************
Guido van Rossume57c96e1996-08-17 19:56:26 +00006
Guido van Rossumf30bec71997-08-29 22:30:45 +00007In earlier versions of Python (up to 1.5a3), scripts or modules that
8needed to use site-specific modules would place ``import site''
9somewhere near the top of their code. Because of the automatic
10import, this is no longer necessary (but code that does it still
11works).
Guido van Rossume57c96e1996-08-17 19:56:26 +000012
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +000013This will append site-specific paths to the module search path. On
Nick Coghlanf2b16f32006-06-12 08:23:02 +000014Unix (including Mac OSX), it starts with sys.prefix and
15sys.exec_prefix (if different) and appends
16lib/python<version>/site-packages as well as lib/site-python.
17On other platforms (such as Windows), it tries each of the
Nick Coghlan3fb55ca2006-06-12 08:19:37 +000018prefixes directly, as well as with lib/site-packages appended. The
Guido van Rossum62b297b1997-09-08 02:14:09 +000019resulting directories, if they exist, are appended to sys.path, and
20also inspected for path configuration files.
Guido van Rossume57c96e1996-08-17 19:56:26 +000021
Guido van Rossumf30bec71997-08-29 22:30:45 +000022A path configuration file is a file whose name has the form
23<package>.pth; its contents are additional directories (one per line)
24to be added to sys.path. Non-existing directories (or
25non-directories) are never added to sys.path; no directory is added to
26sys.path more than once. Blank lines and lines beginning with
Guido van Rossumfacf24b2001-12-17 16:07:06 +000027'#' are skipped. Lines starting with 'import' are executed.
Guido van Rossume57c96e1996-08-17 19:56:26 +000028
Guido van Rossumf30bec71997-08-29 22:30:45 +000029For example, suppose sys.prefix and sys.exec_prefix are set to
Neal Norwitz6e482562006-08-15 04:59:30 +000030/usr/local and there is a directory /usr/local/lib/python2.5/site-packages
Guido van Rossum62b297b1997-09-08 02:14:09 +000031with three subdirectories, foo, bar and spam, and two path
32configuration files, foo.pth and bar.pth. Assume foo.pth contains the
33following:
Guido van Rossumf30bec71997-08-29 22:30:45 +000034
35 # foo package configuration
36 foo
37 bar
38 bletch
39
40and bar.pth contains:
41
42 # bar package configuration
43 bar
44
45Then the following directories are added to sys.path, in this order:
46
Neal Norwitz6e482562006-08-15 04:59:30 +000047 /usr/local/lib/python2.5/site-packages/bar
48 /usr/local/lib/python2.5/site-packages/foo
Guido van Rossumf30bec71997-08-29 22:30:45 +000049
50Note that bletch is omitted because it doesn't exist; bar precedes foo
51because bar.pth comes alphabetically before foo.pth; and spam is
52omitted because it is not mentioned in either path configuration file.
Guido van Rossume57c96e1996-08-17 19:56:26 +000053
54After these path manipulations, an attempt is made to import a module
Guido van Rossumf30bec71997-08-29 22:30:45 +000055named sitecustomize, which can perform arbitrary additional
56site-specific customizations. If this import fails with an
57ImportError exception, it is silently ignored.
Guido van Rossume57c96e1996-08-17 19:56:26 +000058
Guido van Rossume57c96e1996-08-17 19:56:26 +000059"""
60
Brett Cannon0096e262004-06-05 01:12:51 +000061import sys
62import os
63import __builtin__
Guido van Rossume57c96e1996-08-17 19:56:26 +000064
Christian Heimesaf748c32008-05-06 22:41:46 +000065# Prefixes for site-packages; add additional prefixes like /usr/local here
66PREFIXES = [sys.prefix, sys.exec_prefix]
67# Enable per user site-packages directory
68# set it to False to disable the feature or True to force the feature
69ENABLE_USER_SITE = None
Tarek Ziadé764fc232009-08-20 21:23:13 +000070
Christian Heimesaf748c32008-05-06 22:41:46 +000071# for distutils.commands.install
Tarek Ziadé764fc232009-08-20 21:23:13 +000072# These values are initialized by the getuserbase() and getusersitepackages()
73# functions, through the main() function when Python starts.
Christian Heimesaf748c32008-05-06 22:41:46 +000074USER_SITE = None
75USER_BASE = None
76
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000077
Fred Drake38cb9f12000-09-28 16:52:36 +000078def makepath(*paths):
Fred Drake1fb5ce02001-07-02 16:55:42 +000079 dir = os.path.abspath(os.path.join(*paths))
80 return dir, os.path.normcase(dir)
Fred Drake38cb9f12000-09-28 16:52:36 +000081
Christian Heimesaf748c32008-05-06 22:41:46 +000082
Brett Cannon0096e262004-06-05 01:12:51 +000083def abs__file__():
84 """Set all module' __file__ attribute to an absolute path"""
85 for m in sys.modules.values():
Neal Norwitz0c469852006-04-11 07:21:20 +000086 if hasattr(m, '__loader__'):
Phillip J. Eby47032112006-04-11 01:07:43 +000087 continue # don't mess with a PEP 302-supplied __file__
Brett Cannon0096e262004-06-05 01:12:51 +000088 try:
89 m.__file__ = os.path.abspath(m.__file__)
90 except AttributeError:
91 continue
Fred Drake38cb9f12000-09-28 16:52:36 +000092
Christian Heimesaf748c32008-05-06 22:41:46 +000093
Brett Cannon0096e262004-06-05 01:12:51 +000094def removeduppaths():
95 """ Remove duplicate entries from sys.path along with making them
96 absolute"""
97 # This ensures that the initial path provided by the interpreter contains
98 # only absolute pathnames, even if we're running from the build directory.
99 L = []
100 known_paths = set()
101 for dir in sys.path:
102 # Filter out duplicate paths (on case-insensitive file systems also
103 # if they only differ in case); turn relative paths into absolute
104 # paths.
105 dir, dircase = makepath(dir)
106 if not dircase in known_paths:
107 L.append(dir)
108 known_paths.add(dircase)
109 sys.path[:] = L
110 return known_paths
Fred Drake38cb9f12000-09-28 16:52:36 +0000111
Fred Drakee80c0d32002-07-25 20:13:03 +0000112# XXX This should not be part of site.py, since it is needed even when
113# using the -S option for Python. See http://www.python.org/sf/586680
Brett Cannon0096e262004-06-05 01:12:51 +0000114def addbuilddir():
115 """Append ./build/lib.<platform> in case we're running in the build dir
116 (especially for Guido :-)"""
Tarek Ziadé5633a802010-01-23 09:23:15 +0000117 from sysconfig import get_platform
Jeremy Hylton6d58bf62003-07-18 17:45:33 +0000118 s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
Georg Brandlf00b38e2008-01-21 21:19:07 +0000119 if hasattr(sys, 'gettotalrefcount'):
120 s += '-pydebug'
Florent Xicluna176cda12010-03-22 22:52:11 +0000121 s = os.path.join(os.path.dirname(sys.path.pop()), s)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000122 sys.path.append(s)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000123
Christian Heimesaf748c32008-05-06 22:41:46 +0000124
Fred Drake7f5296e2001-07-20 20:06:17 +0000125def _init_pathinfo():
Brett Cannon0096e262004-06-05 01:12:51 +0000126 """Return a set containing all existing directory entries from sys.path"""
127 d = set()
Fred Drake7f5296e2001-07-20 20:06:17 +0000128 for dir in sys.path:
Brett Cannon0096e262004-06-05 01:12:51 +0000129 try:
130 if os.path.isdir(dir):
131 dir, dircase = makepath(dir)
132 d.add(dircase)
133 except TypeError:
Fred Drake7f5296e2001-07-20 20:06:17 +0000134 continue
Brett Cannon0096e262004-06-05 01:12:51 +0000135 return d
Fred Drake7f5296e2001-07-20 20:06:17 +0000136
Christian Heimesaf748c32008-05-06 22:41:46 +0000137
Brett Cannon0096e262004-06-05 01:12:51 +0000138def addpackage(sitedir, name, known_paths):
Georg Brandl8d76cca2007-05-19 18:09:26 +0000139 """Process a .pth file within the site-packages directory:
140 For each line in the file, either combine it with sitedir to a path
141 and add that to known_paths, or execute it if it starts with 'import '.
142 """
Brett Cannon0096e262004-06-05 01:12:51 +0000143 if known_paths is None:
Fred Drake7f5296e2001-07-20 20:06:17 +0000144 _init_pathinfo()
145 reset = 1
146 else:
147 reset = 0
Brett Cannon0096e262004-06-05 01:12:51 +0000148 fullname = os.path.join(sitedir, name)
149 try:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000150 f = open(fullname, "rU")
Brett Cannon0096e262004-06-05 01:12:51 +0000151 except IOError:
152 return
Christian Heimesaf748c32008-05-06 22:41:46 +0000153 with f:
Brett Cannon0096e262004-06-05 01:12:51 +0000154 for line in f:
155 if line.startswith("#"):
156 continue
Christian Heimesaf748c32008-05-06 22:41:46 +0000157 if line.startswith(("import ", "import\t")):
Brett Cannon0096e262004-06-05 01:12:51 +0000158 exec line
159 continue
160 line = line.rstrip()
161 dir, dircase = makepath(sitedir, line)
162 if not dircase in known_paths and os.path.exists(dir):
163 sys.path.append(dir)
164 known_paths.add(dircase)
Brett Cannon0096e262004-06-05 01:12:51 +0000165 if reset:
166 known_paths = None
167 return known_paths
168
Christian Heimesaf748c32008-05-06 22:41:46 +0000169
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000170def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000171 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
172 'sitedir'"""
173 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000174 known_paths = _init_pathinfo()
Brett Cannon0096e262004-06-05 01:12:51 +0000175 reset = 1
176 else:
177 reset = 0
Fred Drake1fb5ce02001-07-02 16:55:42 +0000178 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000179 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000180 sys.path.append(sitedir) # Add path component
Guido van Rossumf30bec71997-08-29 22:30:45 +0000181 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000182 names = os.listdir(sitedir)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000183 except os.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000184 return
Christian Heimesaf748c32008-05-06 22:41:46 +0000185 dotpth = os.extsep + "pth"
186 names = [name for name in names if name.endswith(dotpth)]
187 for name in sorted(names):
188 addpackage(sitedir, name, known_paths)
Fred Drake7f5296e2001-07-20 20:06:17 +0000189 if reset:
Brett Cannon0096e262004-06-05 01:12:51 +0000190 known_paths = None
191 return known_paths
Guido van Rossumf30bec71997-08-29 22:30:45 +0000192
Christian Heimesaf748c32008-05-06 22:41:46 +0000193
194def check_enableusersite():
195 """Check if user site directory is safe for inclusion
196
Andrew M. Kuchling5217d5d2008-05-10 17:36:24 +0000197 The function tests for the command line flag (including environment var),
Christian Heimesaf748c32008-05-06 22:41:46 +0000198 process uid/gid equal to effective uid/gid.
199
200 None: Disabled for security reasons
201 False: Disabled by user (command line option)
202 True: Safe and enabled
203 """
204 if sys.flags.no_user_site:
205 return False
206
207 if hasattr(os, "getuid") and hasattr(os, "geteuid"):
208 # check process uid == effective uid
209 if os.geteuid() != os.getuid():
210 return None
211 if hasattr(os, "getgid") and hasattr(os, "getegid"):
212 # check process gid == effective gid
213 if os.getegid() != os.getgid():
214 return None
215
216 return True
217
Tarek Ziadé764fc232009-08-20 21:23:13 +0000218def getuserbase():
219 """Returns the `user base` directory path.
220
221 The `user base` directory can be used to store data. If the global
222 variable ``USER_BASE`` is not initialized yet, this function will also set
223 it.
224 """
225 global USER_BASE
226 if USER_BASE is not None:
227 return USER_BASE
Tarek Ziadé5633a802010-01-23 09:23:15 +0000228 from sysconfig import get_config_var
229 USER_BASE = get_config_var('userbase')
Tarek Ziadé764fc232009-08-20 21:23:13 +0000230 return USER_BASE
231
232def getusersitepackages():
233 """Returns the user-specific site-packages directory path.
234
235 If the global variable ``USER_SITE`` is not initialized yet, this
236 function will also set it.
237 """
238 global USER_SITE
239 user_base = getuserbase() # this will also set USER_BASE
240
241 if USER_SITE is not None:
242 return USER_SITE
243
Tarek Ziadé5633a802010-01-23 09:23:15 +0000244 from sysconfig import get_path
245 import os
246 USER_SITE = get_path('purelib', '%s_user' % os.name)
Tarek Ziadé764fc232009-08-20 21:23:13 +0000247 return USER_SITE
Christian Heimesaf748c32008-05-06 22:41:46 +0000248
249def addusersitepackages(known_paths):
250 """Add a per user site-package to sys.path
251
252 Each user has its own python directory with site-packages in the
253 home directory.
Christian Heimesaf748c32008-05-06 22:41:46 +0000254 """
Tarek Ziadé764fc232009-08-20 21:23:13 +0000255 # get the per user site-package path
256 # this call will also make sure USER_BASE and USER_SITE are set
257 user_site = getusersitepackages()
Christian Heimesaf748c32008-05-06 22:41:46 +0000258
Tarek Ziadé764fc232009-08-20 21:23:13 +0000259 if ENABLE_USER_SITE and os.path.isdir(user_site):
260 addsitedir(user_site, known_paths)
Christian Heimesaf748c32008-05-06 22:41:46 +0000261 return known_paths
262
Tarek Ziadé764fc232009-08-20 21:23:13 +0000263def getsitepackages():
264 """Returns a list containing all global site-packages directories
265 (and possibly site-python).
Christian Heimesaf748c32008-05-06 22:41:46 +0000266
Tarek Ziadé764fc232009-08-20 21:23:13 +0000267 For each directory present in the global ``PREFIXES``, this function
268 will find its `site-packages` subdirectory depending on the system
269 environment, and will return a list of full paths.
270 """
271 sitepackages = []
Christian Heimesaf748c32008-05-06 22:41:46 +0000272 seen = []
273
274 for prefix in PREFIXES:
275 if not prefix or prefix in seen:
276 continue
277 seen.append(prefix)
278
279 if sys.platform in ('os2emx', 'riscos'):
Tarek Ziadé764fc232009-08-20 21:23:13 +0000280 sitepackages.append(os.path.join(prefix, "Lib", "site-packages"))
Christian Heimesaf748c32008-05-06 22:41:46 +0000281 elif os.sep == '/':
Tarek Ziadé764fc232009-08-20 21:23:13 +0000282 sitepackages.append(os.path.join(prefix, "lib",
Christian Heimesaf748c32008-05-06 22:41:46 +0000283 "python" + sys.version[:3],
284 "site-packages"))
Tarek Ziadé764fc232009-08-20 21:23:13 +0000285 sitepackages.append(os.path.join(prefix, "lib", "site-python"))
Christian Heimesaf748c32008-05-06 22:41:46 +0000286 else:
Tarek Ziadé764fc232009-08-20 21:23:13 +0000287 sitepackages.append(prefix)
288 sitepackages.append(os.path.join(prefix, "lib", "site-packages"))
Christian Heimesaf748c32008-05-06 22:41:46 +0000289 if sys.platform == "darwin":
290 # for framework builds *only* we add the standard Apple
Ronald Oussorene0154ed2009-03-30 23:10:35 +0000291 # locations.
Christian Heimesaf748c32008-05-06 22:41:46 +0000292 if 'Python.framework' in prefix:
Tarek Ziadé764fc232009-08-20 21:23:13 +0000293 sitepackages.append(
Christian Heimesaf748c32008-05-06 22:41:46 +0000294 os.path.expanduser(
295 os.path.join("~", "Library", "Python",
296 sys.version[:3], "site-packages")))
Tarek Ziadé764fc232009-08-20 21:23:13 +0000297 sitepackages.append(
Ronald Oussorene0154ed2009-03-30 23:10:35 +0000298 os.path.join("/Library", "Python",
299 sys.version[:3], "site-packages"))
Tarek Ziadé764fc232009-08-20 21:23:13 +0000300 return sitepackages
Christian Heimesaf748c32008-05-06 22:41:46 +0000301
Tarek Ziadé764fc232009-08-20 21:23:13 +0000302def addsitepackages(known_paths):
303 """Add site-packages (and possibly site-python) to sys.path"""
304 for sitedir in getsitepackages():
Christian Heimesaf748c32008-05-06 22:41:46 +0000305 if os.path.isdir(sitedir):
306 addsitedir(sitedir, known_paths)
307
308 return known_paths
Fred Drake7f5296e2001-07-20 20:06:17 +0000309
Brett Cannon0096e262004-06-05 01:12:51 +0000310def setBEGINLIBPATH():
311 """The OS/2 EMX port has optional extension modules that do double duty
312 as DLLs (and must use the .DLL file extension) for other extensions.
313 The library search path needs to be amended so these will be found
314 during module import. Use BEGINLIBPATH so that these are at the start
315 of the library search path.
Tim Peters4e0e1b62004-07-07 20:54:48 +0000316
Brett Cannon0096e262004-06-05 01:12:51 +0000317 """
Andrew MacIntyre2e8a6e02003-12-02 12:27:25 +0000318 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
319 libpath = os.environ['BEGINLIBPATH'].split(';')
320 if libpath[-1]:
321 libpath.append(dllpath)
322 else:
323 libpath[-1] = dllpath
324 os.environ['BEGINLIBPATH'] = ';'.join(libpath)
325
326
Brett Cannon0096e262004-06-05 01:12:51 +0000327def setquit():
Brian Curtinbc96f322010-04-12 23:30:49 +0000328 """Define new builtins 'quit' and 'exit'.
329
330 These are objects which make the interpreter exit when called.
331 The repr of each object contains a hint at how it works.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000332
Brett Cannon0096e262004-06-05 01:12:51 +0000333 """
334 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000335 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000336 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000337 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000338 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000339 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000340
Georg Brandl24cb0532006-03-09 23:22:06 +0000341 class Quitter(object):
342 def __init__(self, name):
343 self.name = name
344 def __repr__(self):
345 return 'Use %s() or %s to exit' % (self.name, eof)
346 def __call__(self, code=None):
Kurt B. Kaiserd112bc72006-08-16 05:01:42 +0000347 # Shells like IDLE catch the SystemExit, but listen when their
348 # stdin wrapper is closed.
349 try:
350 sys.stdin.close()
351 except:
352 pass
Georg Brandl24cb0532006-03-09 23:22:06 +0000353 raise SystemExit(code)
354 __builtin__.quit = Quitter('quit')
355 __builtin__.exit = Quitter('exit')
Brett Cannon0096e262004-06-05 01:12:51 +0000356
357
358class _Printer(object):
359 """interactive prompt objects for printing the license text, a list of
360 contributors and the copyright notice."""
361
Guido van Rossumd1252392000-09-05 04:39:55 +0000362 MAXLINES = 23
363
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000364 def __init__(self, name, data, files=(), dirs=()):
365 self.__name = name
366 self.__data = data
367 self.__files = files
368 self.__dirs = dirs
369 self.__lines = None
370
371 def __setup(self):
372 if self.__lines:
373 return
374 data = None
375 for dir in self.__dirs:
Brett Cannon0096e262004-06-05 01:12:51 +0000376 for filename in self.__files:
377 filename = os.path.join(dir, filename)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000378 try:
Brett Cannon0096e262004-06-05 01:12:51 +0000379 fp = file(filename, "rU")
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000380 data = fp.read()
381 fp.close()
382 break
383 except IOError:
384 pass
385 if data:
386 break
387 if not data:
388 data = self.__data
389 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000390 self.__linecnt = len(self.__lines)
391
392 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000393 self.__setup()
394 if len(self.__lines) <= self.MAXLINES:
395 return "\n".join(self.__lines)
396 else:
397 return "Type %s() to see the full %s text" % ((self.__name,)*2)
398
399 def __call__(self):
400 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000401 prompt = 'Hit Return for more, or q (and Return) to quit: '
402 lineno = 0
403 while 1:
404 try:
405 for i in range(lineno, lineno + self.MAXLINES):
406 print self.__lines[i]
407 except IndexError:
408 break
409 else:
410 lineno += self.MAXLINES
411 key = None
412 while key is None:
413 key = raw_input(prompt)
414 if key not in ('', 'q'):
415 key = None
416 if key == 'q':
417 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000418
Brett Cannon0096e262004-06-05 01:12:51 +0000419def setcopyright():
420 """Set 'copyright' and 'credits' in __builtin__"""
421 __builtin__.copyright = _Printer("copyright", sys.copyright)
422 if sys.platform[:4] == 'java':
423 __builtin__.credits = _Printer(
424 "credits",
425 "Jython is maintained by the Jython developers (www.jython.org).")
426 else:
427 __builtin__.credits = _Printer("credits", """\
428 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
429 for supporting Python development. See www.python.org for more information.""")
430 here = os.path.dirname(os.__file__)
431 __builtin__.license = _Printer(
432 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
433 ["LICENSE.txt", "LICENSE"],
434 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000435
436
Brett Cannon0096e262004-06-05 01:12:51 +0000437class _Helper(object):
Brian Curtinbc96f322010-04-12 23:30:49 +0000438 """Define the builtin 'help'.
Brett Cannon0096e262004-06-05 01:12:51 +0000439 This is a wrapper around pydoc.help (with a twist).
Guido van Rossum83213cc2001-06-12 16:48:52 +0000440
Brett Cannon0096e262004-06-05 01:12:51 +0000441 """
442
Guido van Rossum83213cc2001-06-12 16:48:52 +0000443 def __repr__(self):
444 return "Type help() for interactive help, " \
445 "or help(object) for help about object."
446 def __call__(self, *args, **kwds):
447 import pydoc
448 return pydoc.help(*args, **kwds)
449
Brett Cannon0096e262004-06-05 01:12:51 +0000450def sethelper():
451 __builtin__.help = _Helper()
452
453def aliasmbcs():
454 """On Windows, some default encodings are not provided by Python,
455 while they are always available as "mbcs" in each locale. Make
456 them usable by aliasing to "mbcs" in such a case."""
457 if sys.platform == 'win32':
458 import locale, codecs
459 enc = locale.getdefaultlocale()[1]
460 if enc.startswith('cp'): # "cp***" ?
461 try:
462 codecs.lookup(enc)
463 except LookupError:
464 import encodings
465 encodings._cache[enc] = encodings._unknown
466 encodings.aliases.aliases[enc] = 'mbcs'
467
468def setencoding():
469 """Set the string encoding used by the Unicode implementation. The
470 default is 'ascii', but if you're willing to experiment, you can
471 change this."""
472 encoding = "ascii" # Default value set by _PyUnicode_Init()
473 if 0:
474 # Enable to support locale aware default string encodings.
475 import locale
476 loc = locale.getdefaultlocale()
477 if loc[1]:
478 encoding = loc[1]
479 if 0:
480 # Enable to switch off string to Unicode coercion and implicit
481 # Unicode to string conversion.
482 encoding = "undefined"
483 if encoding != "ascii":
484 # On Non-Unicode builds this will raise an AttributeError...
485 sys.setdefaultencoding(encoding) # Needs Python Unicode build !
Guido van Rossum83213cc2001-06-12 16:48:52 +0000486
487
Brett Cannon0096e262004-06-05 01:12:51 +0000488def execsitecustomize():
489 """Run custom site specific code, if available."""
490 try:
491 import sitecustomize
492 except ImportError:
493 pass
Victor Stinner66644262010-03-10 22:30:19 +0000494 except Exception:
495 if sys.flags.verbose:
496 sys.excepthook(*sys.exc_info())
497 else:
498 print >>sys.stderr, \
499 "'import sitecustomize' failed; use -v for traceback"
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000500
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000501
Christian Heimesaf748c32008-05-06 22:41:46 +0000502def execusercustomize():
503 """Run custom user specific code, if available."""
504 try:
505 import usercustomize
506 except ImportError:
507 pass
Victor Stinner66644262010-03-10 22:30:19 +0000508 except Exception:
509 if sys.flags.verbose:
510 sys.excepthook(*sys.exc_info())
511 else:
512 print>>sys.stderr, \
Victor Stinner3ec32002010-03-10 22:45:04 +0000513 "'import usercustomize' failed; use -v for traceback"
Christian Heimesaf748c32008-05-06 22:41:46 +0000514
515
Brett Cannon0096e262004-06-05 01:12:51 +0000516def main():
Christian Heimesaf748c32008-05-06 22:41:46 +0000517 global ENABLE_USER_SITE
518
Brett Cannon0096e262004-06-05 01:12:51 +0000519 abs__file__()
Christian Heimesaf748c32008-05-06 22:41:46 +0000520 known_paths = removeduppaths()
Brett Cannon0096e262004-06-05 01:12:51 +0000521 if (os.name == "posix" and sys.path and
522 os.path.basename(sys.path[-1]) == "Modules"):
523 addbuilddir()
Christian Heimesaf748c32008-05-06 22:41:46 +0000524 if ENABLE_USER_SITE is None:
525 ENABLE_USER_SITE = check_enableusersite()
526 known_paths = addusersitepackages(known_paths)
527 known_paths = addsitepackages(known_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000528 if sys.platform == 'os2emx':
529 setBEGINLIBPATH()
530 setquit()
531 setcopyright()
532 sethelper()
533 aliasmbcs()
534 setencoding()
535 execsitecustomize()
Christian Heimesaf748c32008-05-06 22:41:46 +0000536 if ENABLE_USER_SITE:
537 execusercustomize()
Brett Cannon0096e262004-06-05 01:12:51 +0000538 # Remove sys.setdefaultencoding() so that users cannot change the
539 # encoding after initialization. The test for presence is needed when
540 # this module is run as a script, because this code is executed twice.
541 if hasattr(sys, "setdefaultencoding"):
542 del sys.setdefaultencoding
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000543
Brett Cannon0096e262004-06-05 01:12:51 +0000544main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000545
Christian Heimesaf748c32008-05-06 22:41:46 +0000546def _script():
547 help = """\
548 %s [--user-base] [--user-site]
549
550 Without arguments print some useful information
551 With arguments print the value of USER_BASE and/or USER_SITE separated
552 by '%s'.
553
554 Exit codes with --user-base or --user-site:
555 0 - user site directory is enabled
Christian Heimes17433d22008-05-09 12:19:09 +0000556 1 - user site directory is disabled by user
Christian Heimesaf748c32008-05-06 22:41:46 +0000557 2 - uses site directory is disabled by super user
558 or for security reasons
559 >2 - unknown error
560 """
561 args = sys.argv[1:]
562 if not args:
563 print "sys.path = ["
564 for dir in sys.path:
565 print " %r," % (dir,)
566 print "]"
567 print "USER_BASE: %r (%s)" % (USER_BASE,
568 "exists" if os.path.isdir(USER_BASE) else "doesn't exist")
569 print "USER_SITE: %r (%s)" % (USER_SITE,
570 "exists" if os.path.isdir(USER_SITE) else "doesn't exist")
571 print "ENABLE_USER_SITE: %r" % ENABLE_USER_SITE
572 sys.exit(0)
573
574 buffer = []
575 if '--user-base' in args:
576 buffer.append(USER_BASE)
577 if '--user-site' in args:
578 buffer.append(USER_SITE)
579
580 if buffer:
581 print os.pathsep.join(buffer)
582 if ENABLE_USER_SITE:
583 sys.exit(0)
584 elif ENABLE_USER_SITE is False:
585 sys.exit(1)
586 elif ENABLE_USER_SITE is None:
587 sys.exit(2)
588 else:
589 sys.exit(3)
590 else:
591 import textwrap
592 print textwrap.dedent(help % (sys.argv[0], os.pathsep))
593 sys.exit(10)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000594
595if __name__ == '__main__':
Christian Heimesaf748c32008-05-06 22:41:46 +0000596 _script()