blob: 0df1d049380488345f4ec08b0a319b63cfa26289 [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
271 # locations. Currently only per-user, but /Library and
272 # /Network/Library could be added too
273 if 'Python.framework' in prefix:
274 sitedirs.append(
275 os.path.expanduser(
276 os.path.join("~", "Library", "Python",
277 sys.version[:3], "site-packages")))
278
279 for sitedir in sitedirs:
280 if os.path.isdir(sitedir):
281 addsitedir(sitedir, known_paths)
282
283 return known_paths
Fred Drake7f5296e2001-07-20 20:06:17 +0000284
Fred Drake1fb5ce02001-07-02 16:55:42 +0000285
Brett Cannon0096e262004-06-05 01:12:51 +0000286def setBEGINLIBPATH():
287 """The OS/2 EMX port has optional extension modules that do double duty
288 as DLLs (and must use the .DLL file extension) for other extensions.
289 The library search path needs to be amended so these will be found
290 during module import. Use BEGINLIBPATH so that these are at the start
291 of the library search path.
Tim Peters4e0e1b62004-07-07 20:54:48 +0000292
Brett Cannon0096e262004-06-05 01:12:51 +0000293 """
Andrew MacIntyre2e8a6e02003-12-02 12:27:25 +0000294 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
295 libpath = os.environ['BEGINLIBPATH'].split(';')
296 if libpath[-1]:
297 libpath.append(dllpath)
298 else:
299 libpath[-1] = dllpath
300 os.environ['BEGINLIBPATH'] = ';'.join(libpath)
301
302
Brett Cannon0096e262004-06-05 01:12:51 +0000303def setquit():
304 """Define new built-ins 'quit' and 'exit'.
305 These are simply strings that display a hint on how to exit.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000306
Brett Cannon0096e262004-06-05 01:12:51 +0000307 """
308 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000309 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000310 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000311 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000312 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000313 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000314
Georg Brandl24cb0532006-03-09 23:22:06 +0000315 class Quitter(object):
316 def __init__(self, name):
317 self.name = name
318 def __repr__(self):
319 return 'Use %s() or %s to exit' % (self.name, eof)
320 def __call__(self, code=None):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000321 # Shells like IDLE catch the SystemExit, but listen when their
322 # stdin wrapper is closed.
323 try:
Christian Heimes862543a2007-12-31 03:07:24 +0000324 fd = -1
325 if hasattr(sys.stdin, "fileno"):
326 fd = sys.stdin.fileno()
327 if fd != 0:
328 # Don't close stdin if it wraps fd 0
329 sys.stdin.close()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000330 except:
331 pass
Georg Brandl24cb0532006-03-09 23:22:06 +0000332 raise SystemExit(code)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000333 builtins.quit = Quitter('quit')
334 builtins.exit = Quitter('exit')
Brett Cannon0096e262004-06-05 01:12:51 +0000335
336
337class _Printer(object):
338 """interactive prompt objects for printing the license text, a list of
339 contributors and the copyright notice."""
340
Guido van Rossumd1252392000-09-05 04:39:55 +0000341 MAXLINES = 23
342
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000343 def __init__(self, name, data, files=(), dirs=()):
344 self.__name = name
345 self.__data = data
346 self.__files = files
347 self.__dirs = dirs
348 self.__lines = None
349
350 def __setup(self):
351 if self.__lines:
352 return
353 data = None
354 for dir in self.__dirs:
Brett Cannon0096e262004-06-05 01:12:51 +0000355 for filename in self.__files:
356 filename = os.path.join(dir, filename)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000357 try:
Alex Martelli01c77c62006-08-24 02:58:11 +0000358 fp = open(filename, "rU")
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000359 data = fp.read()
360 fp.close()
361 break
362 except IOError:
363 pass
364 if data:
365 break
366 if not data:
367 data = self.__data
368 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000369 self.__linecnt = len(self.__lines)
370
371 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000372 self.__setup()
373 if len(self.__lines) <= self.MAXLINES:
374 return "\n".join(self.__lines)
375 else:
376 return "Type %s() to see the full %s text" % ((self.__name,)*2)
377
378 def __call__(self):
379 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000380 prompt = 'Hit Return for more, or q (and Return) to quit: '
381 lineno = 0
382 while 1:
383 try:
384 for i in range(lineno, lineno + self.MAXLINES):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000385 print(self.__lines[i])
Guido van Rossumd1252392000-09-05 04:39:55 +0000386 except IndexError:
387 break
388 else:
389 lineno += self.MAXLINES
390 key = None
391 while key is None:
Guido van Rossum704b34d2007-12-20 18:42:56 +0000392 key = input(prompt)
Guido van Rossumd1252392000-09-05 04:39:55 +0000393 if key not in ('', 'q'):
394 key = None
395 if key == 'q':
396 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000397
Brett Cannon0096e262004-06-05 01:12:51 +0000398def setcopyright():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000399 """Set 'copyright' and 'credits' in builtins"""
400 builtins.copyright = _Printer("copyright", sys.copyright)
Brett Cannon0096e262004-06-05 01:12:51 +0000401 if sys.platform[:4] == 'java':
Georg Brandl1a3284e2007-12-02 09:40:06 +0000402 builtins.credits = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000403 "credits",
404 "Jython is maintained by the Jython developers (www.jython.org).")
405 else:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000406 builtins.credits = _Printer("credits", """\
Brett Cannon0096e262004-06-05 01:12:51 +0000407 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
408 for supporting Python development. See www.python.org for more information.""")
409 here = os.path.dirname(os.__file__)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000410 builtins.license = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000411 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
412 ["LICENSE.txt", "LICENSE"],
413 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000414
415
Brett Cannon0096e262004-06-05 01:12:51 +0000416class _Helper(object):
417 """Define the built-in 'help'.
418 This is a wrapper around pydoc.help (with a twist).
Guido van Rossum83213cc2001-06-12 16:48:52 +0000419
Brett Cannon0096e262004-06-05 01:12:51 +0000420 """
421
Guido van Rossum83213cc2001-06-12 16:48:52 +0000422 def __repr__(self):
423 return "Type help() for interactive help, " \
424 "or help(object) for help about object."
425 def __call__(self, *args, **kwds):
426 import pydoc
427 return pydoc.help(*args, **kwds)
428
Brett Cannon0096e262004-06-05 01:12:51 +0000429def sethelper():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000430 builtins.help = _Helper()
Brett Cannon0096e262004-06-05 01:12:51 +0000431
432def aliasmbcs():
433 """On Windows, some default encodings are not provided by Python,
434 while they are always available as "mbcs" in each locale. Make
435 them usable by aliasing to "mbcs" in such a case."""
436 if sys.platform == 'win32':
437 import locale, codecs
438 enc = locale.getdefaultlocale()[1]
439 if enc.startswith('cp'): # "cp***" ?
440 try:
441 codecs.lookup(enc)
442 except LookupError:
443 import encodings
444 encodings._cache[enc] = encodings._unknown
445 encodings.aliases.aliases[enc] = 'mbcs'
446
447def setencoding():
448 """Set the string encoding used by the Unicode implementation. The
449 default is 'ascii', but if you're willing to experiment, you can
450 change this."""
451 encoding = "ascii" # Default value set by _PyUnicode_Init()
452 if 0:
453 # Enable to support locale aware default string encodings.
454 import locale
455 loc = locale.getdefaultlocale()
456 if loc[1]:
457 encoding = loc[1]
458 if 0:
459 # Enable to switch off string to Unicode coercion and implicit
460 # Unicode to string conversion.
461 encoding = "undefined"
462 if encoding != "ascii":
463 # On Non-Unicode builds this will raise an AttributeError...
464 sys.setdefaultencoding(encoding) # Needs Python Unicode build !
Guido van Rossum83213cc2001-06-12 16:48:52 +0000465
466
Brett Cannon0096e262004-06-05 01:12:51 +0000467def execsitecustomize():
468 """Run custom site specific code, if available."""
469 try:
470 import sitecustomize
471 except ImportError:
472 pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000473 except Exception as err:
Guido van Rossumc6fe9832006-08-19 00:10:28 +0000474 if os.environ.get("PYTHONVERBOSE"):
475 raise
476 sys.stderr.write(
477 "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
478 "%s: %s\n" %
479 (err.__class__.__name__, err))
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000480
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000481
Christian Heimes8dc226f2008-05-06 23:45:46 +0000482def execusercustomize():
483 """Run custom user specific code, if available."""
484 try:
485 import usercustomize
486 except ImportError:
487 pass
488
489
Brett Cannon0096e262004-06-05 01:12:51 +0000490def main():
Christian Heimes8dc226f2008-05-06 23:45:46 +0000491 global ENABLE_USER_SITE
492
Brett Cannon0096e262004-06-05 01:12:51 +0000493 abs__file__()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000494 known_paths = removeduppaths()
Brett Cannon0096e262004-06-05 01:12:51 +0000495 if (os.name == "posix" and sys.path and
496 os.path.basename(sys.path[-1]) == "Modules"):
497 addbuilddir()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000498 if ENABLE_USER_SITE is None:
499 ENABLE_USER_SITE = check_enableusersite()
500 known_paths = addusersitepackages(known_paths)
501 known_paths = addsitepackages(known_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000502 if sys.platform == 'os2emx':
503 setBEGINLIBPATH()
504 setquit()
505 setcopyright()
506 sethelper()
507 aliasmbcs()
508 setencoding()
509 execsitecustomize()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000510 if ENABLE_USER_SITE:
511 execusercustomize()
Brett Cannon0096e262004-06-05 01:12:51 +0000512 # Remove sys.setdefaultencoding() so that users cannot change the
513 # encoding after initialization. The test for presence is needed when
514 # this module is run as a script, because this code is executed twice.
515 if hasattr(sys, "setdefaultencoding"):
516 del sys.setdefaultencoding
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000517
Brett Cannon0096e262004-06-05 01:12:51 +0000518main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000519
Christian Heimes8dc226f2008-05-06 23:45:46 +0000520def _script():
521 help = """\
522 %s [--user-base] [--user-site]
523
524 Without arguments print some useful information
525 With arguments print the value of USER_BASE and/or USER_SITE separated
526 by '%s'.
527
528 Exit codes with --user-base or --user-site:
529 0 - user site directory is enabled
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000530 1 - user site directory is disabled by user
Christian Heimes8dc226f2008-05-06 23:45:46 +0000531 2 - uses site directory is disabled by super user
532 or for security reasons
533 >2 - unknown error
534 """
535 args = sys.argv[1:]
536 if not args:
537 print("sys.path = [")
538 for dir in sys.path:
539 print(" %r," % (dir,))
540 print("]")
541 print("USER_BASE: %r (%s)" % (USER_BASE,
542 "exists" if os.path.isdir(USER_BASE) else "doesn't exist"))
543 print("USER_SITE: %r (%s)" % (USER_SITE,
544 "exists" if os.path.isdir(USER_SITE) else "doesn't exist"))
545 print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE)
546 sys.exit(0)
547
548 buffer = []
549 if '--user-base' in args:
550 buffer.append(USER_BASE)
551 if '--user-site' in args:
552 buffer.append(USER_SITE)
553
554 if buffer:
555 print(os.pathsep.join(buffer))
556 if ENABLE_USER_SITE:
557 sys.exit(0)
558 elif ENABLE_USER_SITE is False:
559 sys.exit(1)
560 elif ENABLE_USER_SITE is None:
561 sys.exit(2)
562 else:
563 sys.exit(3)
564 else:
565 import textwrap
566 print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
567 sys.exit(10)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000568
569if __name__ == '__main__':
Christian Heimes8dc226f2008-05-06 23:45:46 +0000570 _script()