blob: 7bbd962632b9f92d5b3fb297d12115ff285b3e5d [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
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +00007This will append site-specific paths to the module search path. On
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008Unix (including Mac OSX), it starts with sys.prefix and
9sys.exec_prefix (if different) and appends
10lib/python<version>/site-packages as well as lib/site-python.
11On other platforms (such as Windows), it tries each of the
12prefixes directly, as well as with lib/site-packages appended. The
Guido van Rossum62b297b1997-09-08 02:14:09 +000013resulting directories, if they exist, are appended to sys.path, and
14also inspected for path configuration files.
Guido van Rossume57c96e1996-08-17 19:56:26 +000015
Guido van Rossumf30bec71997-08-29 22:30:45 +000016A path configuration file is a file whose name has the form
17<package>.pth; its contents are additional directories (one per line)
18to be added to sys.path. Non-existing directories (or
19non-directories) are never added to sys.path; no directory is added to
20sys.path more than once. Blank lines and lines beginning with
Guido van Rossumfacf24b2001-12-17 16:07:06 +000021'#' are skipped. Lines starting with 'import' are executed.
Guido van Rossume57c96e1996-08-17 19:56:26 +000022
Guido van Rossumf30bec71997-08-29 22:30:45 +000023For example, suppose sys.prefix and sys.exec_prefix are set to
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000024/usr/local and there is a directory /usr/local/lib/python2.5/site-packages
Guido van Rossum62b297b1997-09-08 02:14:09 +000025with three subdirectories, foo, bar and spam, and two path
26configuration files, foo.pth and bar.pth. Assume foo.pth contains the
27following:
Guido van Rossumf30bec71997-08-29 22:30:45 +000028
29 # foo package configuration
30 foo
31 bar
32 bletch
33
34and bar.pth contains:
35
36 # bar package configuration
37 bar
38
39Then the following directories are added to sys.path, in this order:
40
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000041 /usr/local/lib/python2.5/site-packages/bar
42 /usr/local/lib/python2.5/site-packages/foo
Guido van Rossumf30bec71997-08-29 22:30:45 +000043
44Note that bletch is omitted because it doesn't exist; bar precedes foo
45because bar.pth comes alphabetically before foo.pth; and spam is
46omitted because it is not mentioned in either path configuration file.
Guido van Rossume57c96e1996-08-17 19:56:26 +000047
48After these path manipulations, an attempt is made to import a module
Guido van Rossumf30bec71997-08-29 22:30:45 +000049named sitecustomize, which can perform arbitrary additional
50site-specific customizations. If this import fails with an
51ImportError exception, it is silently ignored.
Guido van Rossume57c96e1996-08-17 19:56:26 +000052
Guido van Rossume57c96e1996-08-17 19:56:26 +000053"""
54
Brett Cannon0096e262004-06-05 01:12:51 +000055import sys
56import os
Georg Brandl1a3284e2007-12-02 09:40:06 +000057import builtins
Guido van Rossume57c96e1996-08-17 19:56:26 +000058
Christian Heimes8dc226f2008-05-06 23:45:46 +000059# Prefixes for site-packages; add additional prefixes like /usr/local here
60PREFIXES = [sys.prefix, sys.exec_prefix]
61# Enable per user site-packages directory
62# set it to False to disable the feature or True to force the feature
63ENABLE_USER_SITE = None
64# for distutils.commands.install
65USER_SITE = None
66USER_BASE = None
67
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000068
Fred Drake38cb9f12000-09-28 16:52:36 +000069def makepath(*paths):
Fred Drake1fb5ce02001-07-02 16:55:42 +000070 dir = os.path.abspath(os.path.join(*paths))
71 return dir, os.path.normcase(dir)
Fred Drake38cb9f12000-09-28 16:52:36 +000072
Christian Heimes8dc226f2008-05-06 23:45:46 +000073
Brett Cannon0096e262004-06-05 01:12:51 +000074def abs__file__():
75 """Set all module' __file__ attribute to an absolute path"""
Guido van Rossum7ac9d402007-05-18 00:24:43 +000076 for m in set(sys.modules.values()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000077 if hasattr(m, '__loader__'):
78 continue # don't mess with a PEP 302-supplied __file__
Brett Cannon0096e262004-06-05 01:12:51 +000079 try:
80 m.__file__ = os.path.abspath(m.__file__)
81 except AttributeError:
82 continue
Fred Drake38cb9f12000-09-28 16:52:36 +000083
Christian Heimes8dc226f2008-05-06 23:45:46 +000084
Brett Cannon0096e262004-06-05 01:12:51 +000085def removeduppaths():
86 """ Remove duplicate entries from sys.path along with making them
87 absolute"""
88 # This ensures that the initial path provided by the interpreter contains
89 # only absolute pathnames, even if we're running from the build directory.
90 L = []
91 known_paths = set()
92 for dir in sys.path:
93 # Filter out duplicate paths (on case-insensitive file systems also
94 # if they only differ in case); turn relative paths into absolute
95 # paths.
96 dir, dircase = makepath(dir)
97 if not dircase in known_paths:
98 L.append(dir)
99 known_paths.add(dircase)
100 sys.path[:] = L
101 return known_paths
Fred Drake38cb9f12000-09-28 16:52:36 +0000102
Fred Drakee80c0d32002-07-25 20:13:03 +0000103# XXX This should not be part of site.py, since it is needed even when
104# using the -S option for Python. See http://www.python.org/sf/586680
Brett Cannon0096e262004-06-05 01:12:51 +0000105def addbuilddir():
106 """Append ./build/lib.<platform> in case we're running in the build dir
107 (especially for Guido :-)"""
Jeremy Hylton6d58bf62003-07-18 17:45:33 +0000108 from distutils.util import get_platform
109 s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
Christian Heimes1af737c2008-01-23 08:24:23 +0000110 if hasattr(sys, 'gettotalrefcount'):
111 s += '-pydebug'
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000112 s = os.path.join(os.path.dirname(sys.path[-1]), s)
113 sys.path.append(s)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000114
Christian Heimes8dc226f2008-05-06 23:45:46 +0000115
Fred Drake7f5296e2001-07-20 20:06:17 +0000116def _init_pathinfo():
Brett Cannon0096e262004-06-05 01:12:51 +0000117 """Return a set containing all existing directory entries from sys.path"""
118 d = set()
Fred Drake7f5296e2001-07-20 20:06:17 +0000119 for dir in sys.path:
Brett Cannon0096e262004-06-05 01:12:51 +0000120 try:
121 if os.path.isdir(dir):
122 dir, dircase = makepath(dir)
123 d.add(dircase)
124 except TypeError:
Fred Drake7f5296e2001-07-20 20:06:17 +0000125 continue
Brett Cannon0096e262004-06-05 01:12:51 +0000126 return d
Fred Drake7f5296e2001-07-20 20:06:17 +0000127
Christian Heimes8dc226f2008-05-06 23:45:46 +0000128
Brett Cannon0096e262004-06-05 01:12:51 +0000129def addpackage(sitedir, name, known_paths):
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000130 """Process a .pth file within the site-packages directory:
131 For each line in the file, either combine it with sitedir to a path
132 and add that to known_paths, or execute it if it starts with 'import '.
133 """
Brett Cannon0096e262004-06-05 01:12:51 +0000134 if known_paths is None:
Fred Drake7f5296e2001-07-20 20:06:17 +0000135 _init_pathinfo()
136 reset = 1
137 else:
138 reset = 0
Brett Cannon0096e262004-06-05 01:12:51 +0000139 fullname = os.path.join(sitedir, name)
140 try:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000141 f = open(fullname, "rU")
Brett Cannon0096e262004-06-05 01:12:51 +0000142 except IOError:
143 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000144 with f:
Brett Cannon0096e262004-06-05 01:12:51 +0000145 for line in f:
146 if line.startswith("#"):
147 continue
Christian Heimes8dc226f2008-05-06 23:45:46 +0000148 if line.startswith(("import ", "import\t")):
Georg Brandl7cae87c2006-09-06 06:51:57 +0000149 exec(line)
Brett Cannon0096e262004-06-05 01:12:51 +0000150 continue
151 line = line.rstrip()
152 dir, dircase = makepath(sitedir, line)
153 if not dircase in known_paths and os.path.exists(dir):
154 sys.path.append(dir)
155 known_paths.add(dircase)
Brett Cannon0096e262004-06-05 01:12:51 +0000156 if reset:
157 known_paths = None
158 return known_paths
159
Christian Heimes8dc226f2008-05-06 23:45:46 +0000160
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000161def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000162 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
163 'sitedir'"""
164 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000165 known_paths = _init_pathinfo()
Brett Cannon0096e262004-06-05 01:12:51 +0000166 reset = 1
167 else:
168 reset = 0
Fred Drake1fb5ce02001-07-02 16:55:42 +0000169 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000170 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000171 sys.path.append(sitedir) # Add path component
Guido van Rossumf30bec71997-08-29 22:30:45 +0000172 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000173 names = os.listdir(sitedir)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000174 except os.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000175 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000176 names = [name for name in names if name.endswith(".pth")]
177 for name in sorted(names):
178 addpackage(sitedir, name, known_paths)
Fred Drake7f5296e2001-07-20 20:06:17 +0000179 if reset:
Brett Cannon0096e262004-06-05 01:12:51 +0000180 known_paths = None
181 return known_paths
Guido van Rossumf30bec71997-08-29 22:30:45 +0000182
Christian Heimes8dc226f2008-05-06 23:45:46 +0000183
184def check_enableusersite():
185 """Check if user site directory is safe for inclusion
186
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000187 The function tests for the command line flag (including environment var),
Christian Heimes8dc226f2008-05-06 23:45:46 +0000188 process uid/gid equal to effective uid/gid.
189
190 None: Disabled for security reasons
191 False: Disabled by user (command line option)
192 True: Safe and enabled
193 """
194 if sys.flags.no_user_site:
195 return False
196
197 if hasattr(os, "getuid") and hasattr(os, "geteuid"):
198 # check process uid == effective uid
199 if os.geteuid() != os.getuid():
200 return None
201 if hasattr(os, "getgid") and hasattr(os, "getegid"):
202 # check process gid == effective gid
203 if os.getegid() != os.getgid():
204 return None
205
206 return True
207
208
209def addusersitepackages(known_paths):
210 """Add a per user site-package to sys.path
211
212 Each user has its own python directory with site-packages in the
213 home directory.
214
215 USER_BASE is the root directory for all Python versions
216
217 USER_SITE is the user specific site-packages directory
218
219 USER_SITE/.. can be used for data.
220 """
221 global USER_BASE, USER_SITE, ENABLE_USER_SITE
222 env_base = os.environ.get("PYTHONUSERBASE", None)
223
224 def joinuser(*args):
225 return os.path.expanduser(os.path.join(*args))
226
227 #if sys.platform in ('os2emx', 'riscos'):
228 # # Don't know what to put here
229 # USER_BASE = ''
230 # USER_SITE = ''
231 if os.name == "nt":
232 base = os.environ.get("APPDATA") or "~"
233 USER_BASE = env_base if env_base else joinuser(base, "Python")
234 USER_SITE = os.path.join(USER_BASE,
235 "Python" + sys.version[0] + sys.version[2],
236 "site-packages")
237 else:
238 USER_BASE = env_base if env_base else joinuser("~", ".local")
239 USER_SITE = os.path.join(USER_BASE, "lib",
240 "python" + sys.version[:3],
241 "site-packages")
242
243 if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
244 addsitedir(USER_SITE, known_paths)
245 return known_paths
246
247
Brett Cannon0096e262004-06-05 01:12:51 +0000248def addsitepackages(known_paths):
249 """Add site-packages (and possibly site-python) to sys.path"""
Christian Heimes8dc226f2008-05-06 23:45:46 +0000250 sitedirs = []
251 seen = []
252
253 for prefix in PREFIXES:
254 if not prefix or prefix in seen:
255 continue
256 seen.append(prefix)
257
258 if sys.platform in ('os2emx', 'riscos'):
259 sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
260 elif os.sep == '/':
261 sitedirs.append(os.path.join(prefix, "lib",
262 "python" + sys.version[:3],
263 "site-packages"))
264 sitedirs.append(os.path.join(prefix, "lib", "site-python"))
265 else:
266 sitedirs.append(prefix)
267 sitedirs.append(os.path.join(prefix, "lib", "site-packages"))
268
269 if sys.platform == "darwin":
270 # for framework builds *only* we add the standard Apple
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000271 # locations.
Christian Heimes8dc226f2008-05-06 23:45:46 +0000272 if 'Python.framework' in prefix:
273 sitedirs.append(
274 os.path.expanduser(
275 os.path.join("~", "Library", "Python",
276 sys.version[:3], "site-packages")))
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000277 sitedirs.append(
278 os.path.join("/Library", "Python",
279 sys.version[:3], "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000280
281 for sitedir in sitedirs:
282 if os.path.isdir(sitedir):
283 addsitedir(sitedir, known_paths)
284
285 return known_paths
Fred Drake7f5296e2001-07-20 20:06:17 +0000286
Fred Drake1fb5ce02001-07-02 16:55:42 +0000287
Brett Cannon0096e262004-06-05 01:12:51 +0000288def setBEGINLIBPATH():
289 """The OS/2 EMX port has optional extension modules that do double duty
290 as DLLs (and must use the .DLL file extension) for other extensions.
291 The library search path needs to be amended so these will be found
292 during module import. Use BEGINLIBPATH so that these are at the start
293 of the library search path.
Tim Peters4e0e1b62004-07-07 20:54:48 +0000294
Brett Cannon0096e262004-06-05 01:12:51 +0000295 """
Andrew MacIntyre2e8a6e02003-12-02 12:27:25 +0000296 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
297 libpath = os.environ['BEGINLIBPATH'].split(';')
298 if libpath[-1]:
299 libpath.append(dllpath)
300 else:
301 libpath[-1] = dllpath
302 os.environ['BEGINLIBPATH'] = ';'.join(libpath)
303
304
Brett Cannon0096e262004-06-05 01:12:51 +0000305def setquit():
306 """Define new built-ins 'quit' and 'exit'.
307 These are simply strings that display a hint on how to exit.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000308
Brett Cannon0096e262004-06-05 01:12:51 +0000309 """
310 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000311 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000312 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000313 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000314 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000315 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000316
Georg Brandl24cb0532006-03-09 23:22:06 +0000317 class Quitter(object):
318 def __init__(self, name):
319 self.name = name
320 def __repr__(self):
321 return 'Use %s() or %s to exit' % (self.name, eof)
322 def __call__(self, code=None):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000323 # Shells like IDLE catch the SystemExit, but listen when their
324 # stdin wrapper is closed.
325 try:
Christian Heimes862543a2007-12-31 03:07:24 +0000326 fd = -1
327 if hasattr(sys.stdin, "fileno"):
328 fd = sys.stdin.fileno()
329 if fd != 0:
330 # Don't close stdin if it wraps fd 0
331 sys.stdin.close()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000332 except:
333 pass
Georg Brandl24cb0532006-03-09 23:22:06 +0000334 raise SystemExit(code)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000335 builtins.quit = Quitter('quit')
336 builtins.exit = Quitter('exit')
Brett Cannon0096e262004-06-05 01:12:51 +0000337
338
339class _Printer(object):
340 """interactive prompt objects for printing the license text, a list of
341 contributors and the copyright notice."""
342
Guido van Rossumd1252392000-09-05 04:39:55 +0000343 MAXLINES = 23
344
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000345 def __init__(self, name, data, files=(), dirs=()):
346 self.__name = name
347 self.__data = data
348 self.__files = files
349 self.__dirs = dirs
350 self.__lines = None
351
352 def __setup(self):
353 if self.__lines:
354 return
355 data = None
356 for dir in self.__dirs:
Brett Cannon0096e262004-06-05 01:12:51 +0000357 for filename in self.__files:
358 filename = os.path.join(dir, filename)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000359 try:
Alex Martelli01c77c62006-08-24 02:58:11 +0000360 fp = open(filename, "rU")
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000361 data = fp.read()
362 fp.close()
363 break
364 except IOError:
365 pass
366 if data:
367 break
368 if not data:
369 data = self.__data
370 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000371 self.__linecnt = len(self.__lines)
372
373 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000374 self.__setup()
375 if len(self.__lines) <= self.MAXLINES:
376 return "\n".join(self.__lines)
377 else:
378 return "Type %s() to see the full %s text" % ((self.__name,)*2)
379
380 def __call__(self):
381 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000382 prompt = 'Hit Return for more, or q (and Return) to quit: '
383 lineno = 0
384 while 1:
385 try:
386 for i in range(lineno, lineno + self.MAXLINES):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000387 print(self.__lines[i])
Guido van Rossumd1252392000-09-05 04:39:55 +0000388 except IndexError:
389 break
390 else:
391 lineno += self.MAXLINES
392 key = None
393 while key is None:
Guido van Rossum704b34d2007-12-20 18:42:56 +0000394 key = input(prompt)
Guido van Rossumd1252392000-09-05 04:39:55 +0000395 if key not in ('', 'q'):
396 key = None
397 if key == 'q':
398 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000399
Brett Cannon0096e262004-06-05 01:12:51 +0000400def setcopyright():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000401 """Set 'copyright' and 'credits' in builtins"""
402 builtins.copyright = _Printer("copyright", sys.copyright)
Brett Cannon0096e262004-06-05 01:12:51 +0000403 if sys.platform[:4] == 'java':
Georg Brandl1a3284e2007-12-02 09:40:06 +0000404 builtins.credits = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000405 "credits",
406 "Jython is maintained by the Jython developers (www.jython.org).")
407 else:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000408 builtins.credits = _Printer("credits", """\
Brett Cannon0096e262004-06-05 01:12:51 +0000409 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
410 for supporting Python development. See www.python.org for more information.""")
411 here = os.path.dirname(os.__file__)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000412 builtins.license = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000413 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
414 ["LICENSE.txt", "LICENSE"],
415 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000416
417
Brett Cannon0096e262004-06-05 01:12:51 +0000418class _Helper(object):
419 """Define the built-in 'help'.
420 This is a wrapper around pydoc.help (with a twist).
Guido van Rossum83213cc2001-06-12 16:48:52 +0000421
Brett Cannon0096e262004-06-05 01:12:51 +0000422 """
423
Guido van Rossum83213cc2001-06-12 16:48:52 +0000424 def __repr__(self):
425 return "Type help() for interactive help, " \
426 "or help(object) for help about object."
427 def __call__(self, *args, **kwds):
428 import pydoc
429 return pydoc.help(*args, **kwds)
430
Brett Cannon0096e262004-06-05 01:12:51 +0000431def sethelper():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000432 builtins.help = _Helper()
Brett Cannon0096e262004-06-05 01:12:51 +0000433
434def aliasmbcs():
435 """On Windows, some default encodings are not provided by Python,
436 while they are always available as "mbcs" in each locale. Make
437 them usable by aliasing to "mbcs" in such a case."""
438 if sys.platform == 'win32':
439 import locale, codecs
440 enc = locale.getdefaultlocale()[1]
441 if enc.startswith('cp'): # "cp***" ?
442 try:
443 codecs.lookup(enc)
444 except LookupError:
445 import encodings
446 encodings._cache[enc] = encodings._unknown
447 encodings.aliases.aliases[enc] = 'mbcs'
448
449def setencoding():
450 """Set the string encoding used by the Unicode implementation. The
451 default is 'ascii', but if you're willing to experiment, you can
452 change this."""
453 encoding = "ascii" # Default value set by _PyUnicode_Init()
454 if 0:
455 # Enable to support locale aware default string encodings.
456 import locale
457 loc = locale.getdefaultlocale()
458 if loc[1]:
459 encoding = loc[1]
460 if 0:
461 # Enable to switch off string to Unicode coercion and implicit
462 # Unicode to string conversion.
463 encoding = "undefined"
464 if encoding != "ascii":
465 # On Non-Unicode builds this will raise an AttributeError...
466 sys.setdefaultencoding(encoding) # Needs Python Unicode build !
Guido van Rossum83213cc2001-06-12 16:48:52 +0000467
468
Brett Cannon0096e262004-06-05 01:12:51 +0000469def execsitecustomize():
470 """Run custom site specific code, if available."""
471 try:
472 import sitecustomize
473 except ImportError:
474 pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000475 except Exception as err:
Guido van Rossumc6fe9832006-08-19 00:10:28 +0000476 if os.environ.get("PYTHONVERBOSE"):
477 raise
478 sys.stderr.write(
479 "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
480 "%s: %s\n" %
481 (err.__class__.__name__, err))
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000482
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000483
Christian Heimes8dc226f2008-05-06 23:45:46 +0000484def execusercustomize():
485 """Run custom user specific code, if available."""
486 try:
487 import usercustomize
488 except ImportError:
489 pass
490
491
Brett Cannon0096e262004-06-05 01:12:51 +0000492def main():
Christian Heimes8dc226f2008-05-06 23:45:46 +0000493 global ENABLE_USER_SITE
494
Brett Cannon0096e262004-06-05 01:12:51 +0000495 abs__file__()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000496 known_paths = removeduppaths()
Brett Cannon0096e262004-06-05 01:12:51 +0000497 if (os.name == "posix" and sys.path and
498 os.path.basename(sys.path[-1]) == "Modules"):
499 addbuilddir()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000500 if ENABLE_USER_SITE is None:
501 ENABLE_USER_SITE = check_enableusersite()
502 known_paths = addusersitepackages(known_paths)
503 known_paths = addsitepackages(known_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000504 if sys.platform == 'os2emx':
505 setBEGINLIBPATH()
506 setquit()
507 setcopyright()
508 sethelper()
509 aliasmbcs()
510 setencoding()
511 execsitecustomize()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000512 if ENABLE_USER_SITE:
513 execusercustomize()
Brett Cannon0096e262004-06-05 01:12:51 +0000514 # Remove sys.setdefaultencoding() so that users cannot change the
515 # encoding after initialization. The test for presence is needed when
516 # this module is run as a script, because this code is executed twice.
517 if hasattr(sys, "setdefaultencoding"):
518 del sys.setdefaultencoding
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000519
Brett Cannon0096e262004-06-05 01:12:51 +0000520main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000521
Christian Heimes8dc226f2008-05-06 23:45:46 +0000522def _script():
523 help = """\
524 %s [--user-base] [--user-site]
525
526 Without arguments print some useful information
527 With arguments print the value of USER_BASE and/or USER_SITE separated
528 by '%s'.
529
530 Exit codes with --user-base or --user-site:
531 0 - user site directory is enabled
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000532 1 - user site directory is disabled by user
Christian Heimes8dc226f2008-05-06 23:45:46 +0000533 2 - uses site directory is disabled by super user
534 or for security reasons
535 >2 - unknown error
536 """
537 args = sys.argv[1:]
538 if not args:
539 print("sys.path = [")
540 for dir in sys.path:
541 print(" %r," % (dir,))
542 print("]")
543 print("USER_BASE: %r (%s)" % (USER_BASE,
544 "exists" if os.path.isdir(USER_BASE) else "doesn't exist"))
545 print("USER_SITE: %r (%s)" % (USER_SITE,
546 "exists" if os.path.isdir(USER_SITE) else "doesn't exist"))
547 print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE)
548 sys.exit(0)
549
550 buffer = []
551 if '--user-base' in args:
552 buffer.append(USER_BASE)
553 if '--user-site' in args:
554 buffer.append(USER_SITE)
555
556 if buffer:
557 print(os.pathsep.join(buffer))
558 if ENABLE_USER_SITE:
559 sys.exit(0)
560 elif ENABLE_USER_SITE is False:
561 sys.exit(1)
562 elif ENABLE_USER_SITE is None:
563 sys.exit(2)
564 else:
565 sys.exit(3)
566 else:
567 import textwrap
568 print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
569 sys.exit(10)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000570
571if __name__ == '__main__':
Christian Heimes8dc226f2008-05-06 23:45:46 +0000572 _script()