blob: 0cc22eba2e579a1b819e1607fdadfd465571f2e7 [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):
Victor Stinner93f5cd42010-10-12 22:56:55 +000070 dir = os.path.join(*paths)
71 try:
72 dir = os.path.abspath(dir)
73 except OSError:
74 pass
Fred Drake1fb5ce02001-07-02 16:55:42 +000075 return dir, os.path.normcase(dir)
Fred Drake38cb9f12000-09-28 16:52:36 +000076
Christian Heimes8dc226f2008-05-06 23:45:46 +000077
Brett Cannon0096e262004-06-05 01:12:51 +000078def abs__file__():
79 """Set all module' __file__ attribute to an absolute path"""
Guido van Rossum7ac9d402007-05-18 00:24:43 +000080 for m in set(sys.modules.values()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000081 if hasattr(m, '__loader__'):
82 continue # don't mess with a PEP 302-supplied __file__
Brett Cannon0096e262004-06-05 01:12:51 +000083 try:
84 m.__file__ = os.path.abspath(m.__file__)
Victor Stinner93f5cd42010-10-12 22:56:55 +000085 except (AttributeError, OSError):
86 pass
Fred Drake38cb9f12000-09-28 16:52:36 +000087
Christian Heimes8dc226f2008-05-06 23:45:46 +000088
Brett Cannon0096e262004-06-05 01:12:51 +000089def removeduppaths():
90 """ Remove duplicate entries from sys.path along with making them
91 absolute"""
92 # This ensures that the initial path provided by the interpreter contains
93 # only absolute pathnames, even if we're running from the build directory.
94 L = []
95 known_paths = set()
96 for dir in sys.path:
97 # Filter out duplicate paths (on case-insensitive file systems also
98 # if they only differ in case); turn relative paths into absolute
99 # paths.
100 dir, dircase = makepath(dir)
101 if not dircase in known_paths:
102 L.append(dir)
103 known_paths.add(dircase)
104 sys.path[:] = L
105 return known_paths
Fred Drake38cb9f12000-09-28 16:52:36 +0000106
Fred Drakee80c0d32002-07-25 20:13:03 +0000107# XXX This should not be part of site.py, since it is needed even when
108# using the -S option for Python. See http://www.python.org/sf/586680
Brett Cannon0096e262004-06-05 01:12:51 +0000109def addbuilddir():
110 """Append ./build/lib.<platform> in case we're running in the build dir
111 (especially for Guido :-)"""
Jeremy Hylton6d58bf62003-07-18 17:45:33 +0000112 from distutils.util import get_platform
113 s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
Christian Heimes1af737c2008-01-23 08:24:23 +0000114 if hasattr(sys, 'gettotalrefcount'):
115 s += '-pydebug'
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000116 s = os.path.join(os.path.dirname(sys.path[-1]), s)
117 sys.path.append(s)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000118
Christian Heimes8dc226f2008-05-06 23:45:46 +0000119
Fred Drake7f5296e2001-07-20 20:06:17 +0000120def _init_pathinfo():
Brett Cannon0096e262004-06-05 01:12:51 +0000121 """Return a set containing all existing directory entries from sys.path"""
122 d = set()
Fred Drake7f5296e2001-07-20 20:06:17 +0000123 for dir in sys.path:
Brett Cannon0096e262004-06-05 01:12:51 +0000124 try:
125 if os.path.isdir(dir):
126 dir, dircase = makepath(dir)
127 d.add(dircase)
128 except TypeError:
Fred Drake7f5296e2001-07-20 20:06:17 +0000129 continue
Brett Cannon0096e262004-06-05 01:12:51 +0000130 return d
Fred Drake7f5296e2001-07-20 20:06:17 +0000131
Christian Heimes8dc226f2008-05-06 23:45:46 +0000132
Brett Cannon0096e262004-06-05 01:12:51 +0000133def addpackage(sitedir, name, known_paths):
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000134 """Process a .pth file within the site-packages directory:
135 For each line in the file, either combine it with sitedir to a path
136 and add that to known_paths, or execute it if it starts with 'import '.
137 """
Brett Cannon0096e262004-06-05 01:12:51 +0000138 if known_paths is None:
Fred Drake7f5296e2001-07-20 20:06:17 +0000139 _init_pathinfo()
140 reset = 1
141 else:
142 reset = 0
Brett Cannon0096e262004-06-05 01:12:51 +0000143 fullname = os.path.join(sitedir, name)
144 try:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000145 f = open(fullname, "rU")
Brett Cannon0096e262004-06-05 01:12:51 +0000146 except IOError:
147 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000148 with f:
Brett Cannon0096e262004-06-05 01:12:51 +0000149 for line in f:
150 if line.startswith("#"):
151 continue
Christian Heimes8dc226f2008-05-06 23:45:46 +0000152 if line.startswith(("import ", "import\t")):
Georg Brandl7cae87c2006-09-06 06:51:57 +0000153 exec(line)
Brett Cannon0096e262004-06-05 01:12:51 +0000154 continue
155 line = line.rstrip()
156 dir, dircase = makepath(sitedir, line)
157 if not dircase in known_paths and os.path.exists(dir):
158 sys.path.append(dir)
159 known_paths.add(dircase)
Brett Cannon0096e262004-06-05 01:12:51 +0000160 if reset:
161 known_paths = None
162 return known_paths
163
Christian Heimes8dc226f2008-05-06 23:45:46 +0000164
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000165def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000166 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
167 'sitedir'"""
168 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000169 known_paths = _init_pathinfo()
Brett Cannon0096e262004-06-05 01:12:51 +0000170 reset = 1
171 else:
172 reset = 0
Fred Drake1fb5ce02001-07-02 16:55:42 +0000173 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000174 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000175 sys.path.append(sitedir) # Add path component
Guido van Rossumf30bec71997-08-29 22:30:45 +0000176 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000177 names = os.listdir(sitedir)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000178 except os.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000179 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000180 names = [name for name in names if name.endswith(".pth")]
181 for name in sorted(names):
182 addpackage(sitedir, name, known_paths)
Fred Drake7f5296e2001-07-20 20:06:17 +0000183 if reset:
Brett Cannon0096e262004-06-05 01:12:51 +0000184 known_paths = None
185 return known_paths
Guido van Rossumf30bec71997-08-29 22:30:45 +0000186
Christian Heimes8dc226f2008-05-06 23:45:46 +0000187
188def check_enableusersite():
189 """Check if user site directory is safe for inclusion
190
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000191 The function tests for the command line flag (including environment var),
Christian Heimes8dc226f2008-05-06 23:45:46 +0000192 process uid/gid equal to effective uid/gid.
193
194 None: Disabled for security reasons
195 False: Disabled by user (command line option)
196 True: Safe and enabled
197 """
198 if sys.flags.no_user_site:
199 return False
200
201 if hasattr(os, "getuid") and hasattr(os, "geteuid"):
202 # check process uid == effective uid
203 if os.geteuid() != os.getuid():
204 return None
205 if hasattr(os, "getgid") and hasattr(os, "getegid"):
206 # check process gid == effective gid
207 if os.getegid() != os.getgid():
208 return None
209
210 return True
211
212
213def addusersitepackages(known_paths):
214 """Add a per user site-package to sys.path
215
216 Each user has its own python directory with site-packages in the
217 home directory.
218
219 USER_BASE is the root directory for all Python versions
220
221 USER_SITE is the user specific site-packages directory
222
223 USER_SITE/.. can be used for data.
224 """
225 global USER_BASE, USER_SITE, ENABLE_USER_SITE
226 env_base = os.environ.get("PYTHONUSERBASE", None)
227
228 def joinuser(*args):
229 return os.path.expanduser(os.path.join(*args))
230
231 #if sys.platform in ('os2emx', 'riscos'):
232 # # Don't know what to put here
233 # USER_BASE = ''
234 # USER_SITE = ''
235 if os.name == "nt":
236 base = os.environ.get("APPDATA") or "~"
237 USER_BASE = env_base if env_base else joinuser(base, "Python")
238 USER_SITE = os.path.join(USER_BASE,
239 "Python" + sys.version[0] + sys.version[2],
240 "site-packages")
241 else:
242 USER_BASE = env_base if env_base else joinuser("~", ".local")
243 USER_SITE = os.path.join(USER_BASE, "lib",
244 "python" + sys.version[:3],
245 "site-packages")
246
247 if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
248 addsitedir(USER_SITE, known_paths)
249 return known_paths
250
251
Brett Cannon0096e262004-06-05 01:12:51 +0000252def addsitepackages(known_paths):
253 """Add site-packages (and possibly site-python) to sys.path"""
Christian Heimes8dc226f2008-05-06 23:45:46 +0000254 sitedirs = []
255 seen = []
256
257 for prefix in PREFIXES:
258 if not prefix or prefix in seen:
259 continue
260 seen.append(prefix)
261
262 if sys.platform in ('os2emx', 'riscos'):
263 sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
264 elif os.sep == '/':
265 sitedirs.append(os.path.join(prefix, "lib",
266 "python" + sys.version[:3],
267 "site-packages"))
268 sitedirs.append(os.path.join(prefix, "lib", "site-python"))
269 else:
270 sitedirs.append(prefix)
271 sitedirs.append(os.path.join(prefix, "lib", "site-packages"))
272
273 if sys.platform == "darwin":
274 # for framework builds *only* we add the standard Apple
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000275 # locations.
Christian Heimes8dc226f2008-05-06 23:45:46 +0000276 if 'Python.framework' in prefix:
277 sitedirs.append(
278 os.path.expanduser(
279 os.path.join("~", "Library", "Python",
280 sys.version[:3], "site-packages")))
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000281 sitedirs.append(
282 os.path.join("/Library", "Python",
283 sys.version[:3], "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000284
285 for sitedir in sitedirs:
286 if os.path.isdir(sitedir):
287 addsitedir(sitedir, known_paths)
288
289 return known_paths
Fred Drake7f5296e2001-07-20 20:06:17 +0000290
Fred Drake1fb5ce02001-07-02 16:55:42 +0000291
Brett Cannon0096e262004-06-05 01:12:51 +0000292def setBEGINLIBPATH():
293 """The OS/2 EMX port has optional extension modules that do double duty
294 as DLLs (and must use the .DLL file extension) for other extensions.
295 The library search path needs to be amended so these will be found
296 during module import. Use BEGINLIBPATH so that these are at the start
297 of the library search path.
Tim Peters4e0e1b62004-07-07 20:54:48 +0000298
Brett Cannon0096e262004-06-05 01:12:51 +0000299 """
Andrew MacIntyre2e8a6e02003-12-02 12:27:25 +0000300 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
301 libpath = os.environ['BEGINLIBPATH'].split(';')
302 if libpath[-1]:
303 libpath.append(dllpath)
304 else:
305 libpath[-1] = dllpath
306 os.environ['BEGINLIBPATH'] = ';'.join(libpath)
307
308
Brett Cannon0096e262004-06-05 01:12:51 +0000309def setquit():
310 """Define new built-ins 'quit' and 'exit'.
311 These are simply strings that display a hint on how to exit.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000312
Brett Cannon0096e262004-06-05 01:12:51 +0000313 """
314 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000315 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000316 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000317 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000318 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000319 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000320
Georg Brandl24cb0532006-03-09 23:22:06 +0000321 class Quitter(object):
322 def __init__(self, name):
323 self.name = name
324 def __repr__(self):
325 return 'Use %s() or %s to exit' % (self.name, eof)
326 def __call__(self, code=None):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000327 # Shells like IDLE catch the SystemExit, but listen when their
328 # stdin wrapper is closed.
329 try:
Christian Heimes862543a2007-12-31 03:07:24 +0000330 fd = -1
331 if hasattr(sys.stdin, "fileno"):
332 fd = sys.stdin.fileno()
333 if fd != 0:
334 # Don't close stdin if it wraps fd 0
335 sys.stdin.close()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000336 except:
337 pass
Georg Brandl24cb0532006-03-09 23:22:06 +0000338 raise SystemExit(code)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000339 builtins.quit = Quitter('quit')
340 builtins.exit = Quitter('exit')
Brett Cannon0096e262004-06-05 01:12:51 +0000341
342
343class _Printer(object):
344 """interactive prompt objects for printing the license text, a list of
345 contributors and the copyright notice."""
346
Guido van Rossumd1252392000-09-05 04:39:55 +0000347 MAXLINES = 23
348
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000349 def __init__(self, name, data, files=(), dirs=()):
350 self.__name = name
351 self.__data = data
352 self.__files = files
353 self.__dirs = dirs
354 self.__lines = None
355
356 def __setup(self):
357 if self.__lines:
358 return
359 data = None
360 for dir in self.__dirs:
Brett Cannon0096e262004-06-05 01:12:51 +0000361 for filename in self.__files:
362 filename = os.path.join(dir, filename)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000363 try:
Alex Martelli01c77c62006-08-24 02:58:11 +0000364 fp = open(filename, "rU")
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000365 data = fp.read()
366 fp.close()
367 break
368 except IOError:
369 pass
370 if data:
371 break
372 if not data:
373 data = self.__data
374 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000375 self.__linecnt = len(self.__lines)
376
377 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000378 self.__setup()
379 if len(self.__lines) <= self.MAXLINES:
380 return "\n".join(self.__lines)
381 else:
382 return "Type %s() to see the full %s text" % ((self.__name,)*2)
383
384 def __call__(self):
385 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000386 prompt = 'Hit Return for more, or q (and Return) to quit: '
387 lineno = 0
388 while 1:
389 try:
390 for i in range(lineno, lineno + self.MAXLINES):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000391 print(self.__lines[i])
Guido van Rossumd1252392000-09-05 04:39:55 +0000392 except IndexError:
393 break
394 else:
395 lineno += self.MAXLINES
396 key = None
397 while key is None:
Guido van Rossum704b34d2007-12-20 18:42:56 +0000398 key = input(prompt)
Guido van Rossumd1252392000-09-05 04:39:55 +0000399 if key not in ('', 'q'):
400 key = None
401 if key == 'q':
402 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000403
Brett Cannon0096e262004-06-05 01:12:51 +0000404def setcopyright():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000405 """Set 'copyright' and 'credits' in builtins"""
406 builtins.copyright = _Printer("copyright", sys.copyright)
Brett Cannon0096e262004-06-05 01:12:51 +0000407 if sys.platform[:4] == 'java':
Georg Brandl1a3284e2007-12-02 09:40:06 +0000408 builtins.credits = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000409 "credits",
410 "Jython is maintained by the Jython developers (www.jython.org).")
411 else:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000412 builtins.credits = _Printer("credits", """\
Brett Cannon0096e262004-06-05 01:12:51 +0000413 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
414 for supporting Python development. See www.python.org for more information.""")
415 here = os.path.dirname(os.__file__)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000416 builtins.license = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000417 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
418 ["LICENSE.txt", "LICENSE"],
419 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000420
421
Brett Cannon0096e262004-06-05 01:12:51 +0000422class _Helper(object):
423 """Define the built-in 'help'.
424 This is a wrapper around pydoc.help (with a twist).
Guido van Rossum83213cc2001-06-12 16:48:52 +0000425
Brett Cannon0096e262004-06-05 01:12:51 +0000426 """
427
Guido van Rossum83213cc2001-06-12 16:48:52 +0000428 def __repr__(self):
429 return "Type help() for interactive help, " \
430 "or help(object) for help about object."
431 def __call__(self, *args, **kwds):
432 import pydoc
433 return pydoc.help(*args, **kwds)
434
Brett Cannon0096e262004-06-05 01:12:51 +0000435def sethelper():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000436 builtins.help = _Helper()
Brett Cannon0096e262004-06-05 01:12:51 +0000437
438def aliasmbcs():
439 """On Windows, some default encodings are not provided by Python,
440 while they are always available as "mbcs" in each locale. Make
441 them usable by aliasing to "mbcs" in such a case."""
442 if sys.platform == 'win32':
443 import locale, codecs
444 enc = locale.getdefaultlocale()[1]
445 if enc.startswith('cp'): # "cp***" ?
446 try:
447 codecs.lookup(enc)
448 except LookupError:
449 import encodings
450 encodings._cache[enc] = encodings._unknown
451 encodings.aliases.aliases[enc] = 'mbcs'
452
453def setencoding():
454 """Set the string encoding used by the Unicode implementation. The
455 default is 'ascii', but if you're willing to experiment, you can
456 change this."""
457 encoding = "ascii" # Default value set by _PyUnicode_Init()
458 if 0:
459 # Enable to support locale aware default string encodings.
460 import locale
461 loc = locale.getdefaultlocale()
462 if loc[1]:
463 encoding = loc[1]
464 if 0:
465 # Enable to switch off string to Unicode coercion and implicit
466 # Unicode to string conversion.
467 encoding = "undefined"
468 if encoding != "ascii":
469 # On Non-Unicode builds this will raise an AttributeError...
470 sys.setdefaultencoding(encoding) # Needs Python Unicode build !
Guido van Rossum83213cc2001-06-12 16:48:52 +0000471
472
Brett Cannon0096e262004-06-05 01:12:51 +0000473def execsitecustomize():
474 """Run custom site specific code, if available."""
475 try:
476 import sitecustomize
477 except ImportError:
478 pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000479 except Exception as err:
Guido van Rossumc6fe9832006-08-19 00:10:28 +0000480 if os.environ.get("PYTHONVERBOSE"):
Victor Stinnerffbc2f62010-03-21 21:48:45 +0000481 sys.excepthook(*sys.exc_info())
482 else:
483 sys.stderr.write(
484 "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
485 "%s: %s\n" %
486 (err.__class__.__name__, err))
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000487
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000488
Christian Heimes8dc226f2008-05-06 23:45:46 +0000489def execusercustomize():
490 """Run custom user specific code, if available."""
491 try:
492 import usercustomize
493 except ImportError:
494 pass
Victor Stinnerffbc2f62010-03-21 21:48:45 +0000495 except Exception as err:
496 if os.environ.get("PYTHONVERBOSE"):
497 sys.excepthook(*sys.exc_info())
498 else:
499 sys.stderr.write(
500 "Error in usercustomize; set PYTHONVERBOSE for traceback:\n"
501 "%s: %s\n" %
502 (err.__class__.__name__, err))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000503
504
Brett Cannon0096e262004-06-05 01:12:51 +0000505def main():
Christian Heimes8dc226f2008-05-06 23:45:46 +0000506 global ENABLE_USER_SITE
507
Brett Cannon0096e262004-06-05 01:12:51 +0000508 abs__file__()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000509 known_paths = removeduppaths()
Brett Cannon0096e262004-06-05 01:12:51 +0000510 if (os.name == "posix" and sys.path and
511 os.path.basename(sys.path[-1]) == "Modules"):
512 addbuilddir()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000513 if ENABLE_USER_SITE is None:
514 ENABLE_USER_SITE = check_enableusersite()
515 known_paths = addusersitepackages(known_paths)
516 known_paths = addsitepackages(known_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000517 if sys.platform == 'os2emx':
518 setBEGINLIBPATH()
519 setquit()
520 setcopyright()
521 sethelper()
522 aliasmbcs()
523 setencoding()
524 execsitecustomize()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000525 if ENABLE_USER_SITE:
526 execusercustomize()
Brett Cannon0096e262004-06-05 01:12:51 +0000527 # Remove sys.setdefaultencoding() so that users cannot change the
528 # encoding after initialization. The test for presence is needed when
529 # this module is run as a script, because this code is executed twice.
530 if hasattr(sys, "setdefaultencoding"):
531 del sys.setdefaultencoding
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000532
Brett Cannon0096e262004-06-05 01:12:51 +0000533main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000534
Christian Heimes8dc226f2008-05-06 23:45:46 +0000535def _script():
536 help = """\
537 %s [--user-base] [--user-site]
538
539 Without arguments print some useful information
540 With arguments print the value of USER_BASE and/or USER_SITE separated
541 by '%s'.
542
543 Exit codes with --user-base or --user-site:
544 0 - user site directory is enabled
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000545 1 - user site directory is disabled by user
Christian Heimes8dc226f2008-05-06 23:45:46 +0000546 2 - uses site directory is disabled by super user
547 or for security reasons
548 >2 - unknown error
549 """
550 args = sys.argv[1:]
551 if not args:
552 print("sys.path = [")
553 for dir in sys.path:
554 print(" %r," % (dir,))
555 print("]")
556 print("USER_BASE: %r (%s)" % (USER_BASE,
557 "exists" if os.path.isdir(USER_BASE) else "doesn't exist"))
558 print("USER_SITE: %r (%s)" % (USER_SITE,
559 "exists" if os.path.isdir(USER_SITE) else "doesn't exist"))
560 print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE)
561 sys.exit(0)
562
563 buffer = []
564 if '--user-base' in args:
565 buffer.append(USER_BASE)
566 if '--user-site' in args:
567 buffer.append(USER_SITE)
568
569 if buffer:
570 print(os.pathsep.join(buffer))
571 if ENABLE_USER_SITE:
572 sys.exit(0)
573 elif ENABLE_USER_SITE is False:
574 sys.exit(1)
575 elif ENABLE_USER_SITE is None:
576 sys.exit(2)
577 else:
578 sys.exit(3)
579 else:
580 import textwrap
581 print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
582 sys.exit(10)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000583
584if __name__ == '__main__':
Christian Heimes8dc226f2008-05-06 23:45:46 +0000585 _script()