blob: abe668759cd4ad37e5745247c6a0ce5d2c459535 [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
70# for distutils.commands.install
71USER_SITE = None
72USER_BASE = None
73
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000074
Fred Drake38cb9f12000-09-28 16:52:36 +000075def makepath(*paths):
Fred Drake1fb5ce02001-07-02 16:55:42 +000076 dir = os.path.abspath(os.path.join(*paths))
77 return dir, os.path.normcase(dir)
Fred Drake38cb9f12000-09-28 16:52:36 +000078
Christian Heimesaf748c32008-05-06 22:41:46 +000079
Brett Cannon0096e262004-06-05 01:12:51 +000080def abs__file__():
81 """Set all module' __file__ attribute to an absolute path"""
82 for m in sys.modules.values():
Neal Norwitz0c469852006-04-11 07:21:20 +000083 if hasattr(m, '__loader__'):
Phillip J. Eby47032112006-04-11 01:07:43 +000084 continue # don't mess with a PEP 302-supplied __file__
Brett Cannon0096e262004-06-05 01:12:51 +000085 try:
86 m.__file__ = os.path.abspath(m.__file__)
87 except AttributeError:
88 continue
Fred Drake38cb9f12000-09-28 16:52:36 +000089
Christian Heimesaf748c32008-05-06 22:41:46 +000090
Brett Cannon0096e262004-06-05 01:12:51 +000091def removeduppaths():
92 """ Remove duplicate entries from sys.path along with making them
93 absolute"""
94 # This ensures that the initial path provided by the interpreter contains
95 # only absolute pathnames, even if we're running from the build directory.
96 L = []
97 known_paths = set()
98 for dir in sys.path:
99 # Filter out duplicate paths (on case-insensitive file systems also
100 # if they only differ in case); turn relative paths into absolute
101 # paths.
102 dir, dircase = makepath(dir)
103 if not dircase in known_paths:
104 L.append(dir)
105 known_paths.add(dircase)
106 sys.path[:] = L
107 return known_paths
Fred Drake38cb9f12000-09-28 16:52:36 +0000108
Fred Drakee80c0d32002-07-25 20:13:03 +0000109# XXX This should not be part of site.py, since it is needed even when
110# using the -S option for Python. See http://www.python.org/sf/586680
Brett Cannon0096e262004-06-05 01:12:51 +0000111def addbuilddir():
112 """Append ./build/lib.<platform> in case we're running in the build dir
113 (especially for Guido :-)"""
Jeremy Hylton6d58bf62003-07-18 17:45:33 +0000114 from distutils.util import get_platform
115 s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
Georg Brandlf00b38e2008-01-21 21:19:07 +0000116 if hasattr(sys, 'gettotalrefcount'):
117 s += '-pydebug'
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000118 s = os.path.join(os.path.dirname(sys.path[-1]), s)
119 sys.path.append(s)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000120
Christian Heimesaf748c32008-05-06 22:41:46 +0000121
Fred Drake7f5296e2001-07-20 20:06:17 +0000122def _init_pathinfo():
Brett Cannon0096e262004-06-05 01:12:51 +0000123 """Return a set containing all existing directory entries from sys.path"""
124 d = set()
Fred Drake7f5296e2001-07-20 20:06:17 +0000125 for dir in sys.path:
Brett Cannon0096e262004-06-05 01:12:51 +0000126 try:
127 if os.path.isdir(dir):
128 dir, dircase = makepath(dir)
129 d.add(dircase)
130 except TypeError:
Fred Drake7f5296e2001-07-20 20:06:17 +0000131 continue
Brett Cannon0096e262004-06-05 01:12:51 +0000132 return d
Fred Drake7f5296e2001-07-20 20:06:17 +0000133
Christian Heimesaf748c32008-05-06 22:41:46 +0000134
Brett Cannon0096e262004-06-05 01:12:51 +0000135def addpackage(sitedir, name, known_paths):
Georg Brandl8d76cca2007-05-19 18:09:26 +0000136 """Process a .pth file within the site-packages directory:
137 For each line in the file, either combine it with sitedir to a path
138 and add that to known_paths, or execute it if it starts with 'import '.
139 """
Brett Cannon0096e262004-06-05 01:12:51 +0000140 if known_paths is None:
Fred Drake7f5296e2001-07-20 20:06:17 +0000141 _init_pathinfo()
142 reset = 1
143 else:
144 reset = 0
Brett Cannon0096e262004-06-05 01:12:51 +0000145 fullname = os.path.join(sitedir, name)
146 try:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000147 f = open(fullname, "rU")
Brett Cannon0096e262004-06-05 01:12:51 +0000148 except IOError:
149 return
Christian Heimesaf748c32008-05-06 22:41:46 +0000150 with f:
Brett Cannon0096e262004-06-05 01:12:51 +0000151 for line in f:
152 if line.startswith("#"):
153 continue
Christian Heimesaf748c32008-05-06 22:41:46 +0000154 if line.startswith(("import ", "import\t")):
Brett Cannon0096e262004-06-05 01:12:51 +0000155 exec line
156 continue
157 line = line.rstrip()
158 dir, dircase = makepath(sitedir, line)
159 if not dircase in known_paths and os.path.exists(dir):
160 sys.path.append(dir)
161 known_paths.add(dircase)
Brett Cannon0096e262004-06-05 01:12:51 +0000162 if reset:
163 known_paths = None
164 return known_paths
165
Christian Heimesaf748c32008-05-06 22:41:46 +0000166
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000167def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000168 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
169 'sitedir'"""
170 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000171 known_paths = _init_pathinfo()
Brett Cannon0096e262004-06-05 01:12:51 +0000172 reset = 1
173 else:
174 reset = 0
Fred Drake1fb5ce02001-07-02 16:55:42 +0000175 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000176 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000177 sys.path.append(sitedir) # Add path component
Guido van Rossumf30bec71997-08-29 22:30:45 +0000178 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000179 names = os.listdir(sitedir)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000180 except os.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000181 return
Christian Heimesaf748c32008-05-06 22:41:46 +0000182 dotpth = os.extsep + "pth"
183 names = [name for name in names if name.endswith(dotpth)]
184 for name in sorted(names):
185 addpackage(sitedir, name, known_paths)
Fred Drake7f5296e2001-07-20 20:06:17 +0000186 if reset:
Brett Cannon0096e262004-06-05 01:12:51 +0000187 known_paths = None
188 return known_paths
Guido van Rossumf30bec71997-08-29 22:30:45 +0000189
Christian Heimesaf748c32008-05-06 22:41:46 +0000190
191def check_enableusersite():
192 """Check if user site directory is safe for inclusion
193
Andrew M. Kuchling5217d5d2008-05-10 17:36:24 +0000194 The function tests for the command line flag (including environment var),
Christian Heimesaf748c32008-05-06 22:41:46 +0000195 process uid/gid equal to effective uid/gid.
196
197 None: Disabled for security reasons
198 False: Disabled by user (command line option)
199 True: Safe and enabled
200 """
201 if sys.flags.no_user_site:
202 return False
203
204 if hasattr(os, "getuid") and hasattr(os, "geteuid"):
205 # check process uid == effective uid
206 if os.geteuid() != os.getuid():
207 return None
208 if hasattr(os, "getgid") and hasattr(os, "getegid"):
209 # check process gid == effective gid
210 if os.getegid() != os.getgid():
211 return None
212
213 return True
214
215
216def addusersitepackages(known_paths):
217 """Add a per user site-package to sys.path
218
219 Each user has its own python directory with site-packages in the
220 home directory.
221
222 USER_BASE is the root directory for all Python versions
223
224 USER_SITE is the user specific site-packages directory
225
226 USER_SITE/.. can be used for data.
227 """
228 global USER_BASE, USER_SITE, ENABLE_USER_SITE
229 env_base = os.environ.get("PYTHONUSERBASE", None)
230
231 def joinuser(*args):
232 return os.path.expanduser(os.path.join(*args))
233
234 #if sys.platform in ('os2emx', 'riscos'):
235 # # Don't know what to put here
236 # USER_BASE = ''
237 # USER_SITE = ''
238 if os.name == "nt":
239 base = os.environ.get("APPDATA") or "~"
240 USER_BASE = env_base if env_base else joinuser(base, "Python")
241 USER_SITE = os.path.join(USER_BASE,
242 "Python" + sys.version[0] + sys.version[2],
243 "site-packages")
244 else:
245 USER_BASE = env_base if env_base else joinuser("~", ".local")
246 USER_SITE = os.path.join(USER_BASE, "lib",
247 "python" + sys.version[:3],
248 "site-packages")
249
250 if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
251 addsitedir(USER_SITE, known_paths)
252 return known_paths
253
254
Brett Cannon0096e262004-06-05 01:12:51 +0000255def addsitepackages(known_paths):
256 """Add site-packages (and possibly site-python) to sys.path"""
Christian Heimesaf748c32008-05-06 22:41:46 +0000257 sitedirs = []
258 seen = []
259
260 for prefix in PREFIXES:
261 if not prefix or prefix in seen:
262 continue
263 seen.append(prefix)
264
265 if sys.platform in ('os2emx', 'riscos'):
266 sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
267 elif os.sep == '/':
268 sitedirs.append(os.path.join(prefix, "lib",
269 "python" + sys.version[:3],
270 "site-packages"))
271 sitedirs.append(os.path.join(prefix, "lib", "site-python"))
272 else:
273 sitedirs.append(prefix)
274 sitedirs.append(os.path.join(prefix, "lib", "site-packages"))
275
276 if sys.platform == "darwin":
277 # for framework builds *only* we add the standard Apple
Ronald Oussorene0154ed2009-03-30 23:10:35 +0000278 # locations.
Christian Heimesaf748c32008-05-06 22:41:46 +0000279 if 'Python.framework' in prefix:
280 sitedirs.append(
281 os.path.expanduser(
282 os.path.join("~", "Library", "Python",
283 sys.version[:3], "site-packages")))
Ronald Oussorene0154ed2009-03-30 23:10:35 +0000284 sitedirs.append(
285 os.path.join("/Library", "Python",
286 sys.version[:3], "site-packages"))
Christian Heimesaf748c32008-05-06 22:41:46 +0000287
288 for sitedir in sitedirs:
289 if os.path.isdir(sitedir):
290 addsitedir(sitedir, known_paths)
291
292 return known_paths
Fred Drake7f5296e2001-07-20 20:06:17 +0000293
Fred Drake1fb5ce02001-07-02 16:55:42 +0000294
Brett Cannon0096e262004-06-05 01:12:51 +0000295def setBEGINLIBPATH():
296 """The OS/2 EMX port has optional extension modules that do double duty
297 as DLLs (and must use the .DLL file extension) for other extensions.
298 The library search path needs to be amended so these will be found
299 during module import. Use BEGINLIBPATH so that these are at the start
300 of the library search path.
Tim Peters4e0e1b62004-07-07 20:54:48 +0000301
Brett Cannon0096e262004-06-05 01:12:51 +0000302 """
Andrew MacIntyre2e8a6e02003-12-02 12:27:25 +0000303 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
304 libpath = os.environ['BEGINLIBPATH'].split(';')
305 if libpath[-1]:
306 libpath.append(dllpath)
307 else:
308 libpath[-1] = dllpath
309 os.environ['BEGINLIBPATH'] = ';'.join(libpath)
310
311
Brett Cannon0096e262004-06-05 01:12:51 +0000312def setquit():
313 """Define new built-ins 'quit' and 'exit'.
314 These are simply strings that display a hint on how to exit.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000315
Brett Cannon0096e262004-06-05 01:12:51 +0000316 """
317 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000318 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000319 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000320 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000321 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000322 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000323
Georg Brandl24cb0532006-03-09 23:22:06 +0000324 class Quitter(object):
325 def __init__(self, name):
326 self.name = name
327 def __repr__(self):
328 return 'Use %s() or %s to exit' % (self.name, eof)
329 def __call__(self, code=None):
Kurt B. Kaiserd112bc72006-08-16 05:01:42 +0000330 # Shells like IDLE catch the SystemExit, but listen when their
331 # stdin wrapper is closed.
332 try:
333 sys.stdin.close()
334 except:
335 pass
Georg Brandl24cb0532006-03-09 23:22:06 +0000336 raise SystemExit(code)
337 __builtin__.quit = Quitter('quit')
338 __builtin__.exit = Quitter('exit')
Brett Cannon0096e262004-06-05 01:12:51 +0000339
340
341class _Printer(object):
342 """interactive prompt objects for printing the license text, a list of
343 contributors and the copyright notice."""
344
Guido van Rossumd1252392000-09-05 04:39:55 +0000345 MAXLINES = 23
346
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000347 def __init__(self, name, data, files=(), dirs=()):
348 self.__name = name
349 self.__data = data
350 self.__files = files
351 self.__dirs = dirs
352 self.__lines = None
353
354 def __setup(self):
355 if self.__lines:
356 return
357 data = None
358 for dir in self.__dirs:
Brett Cannon0096e262004-06-05 01:12:51 +0000359 for filename in self.__files:
360 filename = os.path.join(dir, filename)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000361 try:
Brett Cannon0096e262004-06-05 01:12:51 +0000362 fp = file(filename, "rU")
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000363 data = fp.read()
364 fp.close()
365 break
366 except IOError:
367 pass
368 if data:
369 break
370 if not data:
371 data = self.__data
372 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000373 self.__linecnt = len(self.__lines)
374
375 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000376 self.__setup()
377 if len(self.__lines) <= self.MAXLINES:
378 return "\n".join(self.__lines)
379 else:
380 return "Type %s() to see the full %s text" % ((self.__name,)*2)
381
382 def __call__(self):
383 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000384 prompt = 'Hit Return for more, or q (and Return) to quit: '
385 lineno = 0
386 while 1:
387 try:
388 for i in range(lineno, lineno + self.MAXLINES):
389 print self.__lines[i]
390 except IndexError:
391 break
392 else:
393 lineno += self.MAXLINES
394 key = None
395 while key is None:
396 key = raw_input(prompt)
397 if key not in ('', 'q'):
398 key = None
399 if key == 'q':
400 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000401
Brett Cannon0096e262004-06-05 01:12:51 +0000402def setcopyright():
403 """Set 'copyright' and 'credits' in __builtin__"""
404 __builtin__.copyright = _Printer("copyright", sys.copyright)
405 if sys.platform[:4] == 'java':
406 __builtin__.credits = _Printer(
407 "credits",
408 "Jython is maintained by the Jython developers (www.jython.org).")
409 else:
410 __builtin__.credits = _Printer("credits", """\
411 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
412 for supporting Python development. See www.python.org for more information.""")
413 here = os.path.dirname(os.__file__)
414 __builtin__.license = _Printer(
415 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
416 ["LICENSE.txt", "LICENSE"],
417 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000418
419
Brett Cannon0096e262004-06-05 01:12:51 +0000420class _Helper(object):
421 """Define the built-in 'help'.
422 This is a wrapper around pydoc.help (with a twist).
Guido van Rossum83213cc2001-06-12 16:48:52 +0000423
Brett Cannon0096e262004-06-05 01:12:51 +0000424 """
425
Guido van Rossum83213cc2001-06-12 16:48:52 +0000426 def __repr__(self):
427 return "Type help() for interactive help, " \
428 "or help(object) for help about object."
429 def __call__(self, *args, **kwds):
430 import pydoc
431 return pydoc.help(*args, **kwds)
432
Brett Cannon0096e262004-06-05 01:12:51 +0000433def sethelper():
434 __builtin__.help = _Helper()
435
436def aliasmbcs():
437 """On Windows, some default encodings are not provided by Python,
438 while they are always available as "mbcs" in each locale. Make
439 them usable by aliasing to "mbcs" in such a case."""
440 if sys.platform == 'win32':
441 import locale, codecs
442 enc = locale.getdefaultlocale()[1]
443 if enc.startswith('cp'): # "cp***" ?
444 try:
445 codecs.lookup(enc)
446 except LookupError:
447 import encodings
448 encodings._cache[enc] = encodings._unknown
449 encodings.aliases.aliases[enc] = 'mbcs'
450
451def setencoding():
452 """Set the string encoding used by the Unicode implementation. The
453 default is 'ascii', but if you're willing to experiment, you can
454 change this."""
455 encoding = "ascii" # Default value set by _PyUnicode_Init()
456 if 0:
457 # Enable to support locale aware default string encodings.
458 import locale
459 loc = locale.getdefaultlocale()
460 if loc[1]:
461 encoding = loc[1]
462 if 0:
463 # Enable to switch off string to Unicode coercion and implicit
464 # Unicode to string conversion.
465 encoding = "undefined"
466 if encoding != "ascii":
467 # On Non-Unicode builds this will raise an AttributeError...
468 sys.setdefaultencoding(encoding) # Needs Python Unicode build !
Guido van Rossum83213cc2001-06-12 16:48:52 +0000469
470
Brett Cannon0096e262004-06-05 01:12:51 +0000471def execsitecustomize():
472 """Run custom site specific code, if available."""
473 try:
474 import sitecustomize
475 except ImportError:
476 pass
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000477
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000478
Christian Heimesaf748c32008-05-06 22:41:46 +0000479def execusercustomize():
480 """Run custom user specific code, if available."""
481 try:
482 import usercustomize
483 except ImportError:
484 pass
485
486
Brett Cannon0096e262004-06-05 01:12:51 +0000487def main():
Christian Heimesaf748c32008-05-06 22:41:46 +0000488 global ENABLE_USER_SITE
489
Brett Cannon0096e262004-06-05 01:12:51 +0000490 abs__file__()
Christian Heimesaf748c32008-05-06 22:41:46 +0000491 known_paths = removeduppaths()
Brett Cannon0096e262004-06-05 01:12:51 +0000492 if (os.name == "posix" and sys.path and
493 os.path.basename(sys.path[-1]) == "Modules"):
494 addbuilddir()
Christian Heimesaf748c32008-05-06 22:41:46 +0000495 if ENABLE_USER_SITE is None:
496 ENABLE_USER_SITE = check_enableusersite()
497 known_paths = addusersitepackages(known_paths)
498 known_paths = addsitepackages(known_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000499 if sys.platform == 'os2emx':
500 setBEGINLIBPATH()
501 setquit()
502 setcopyright()
503 sethelper()
504 aliasmbcs()
505 setencoding()
506 execsitecustomize()
Christian Heimesaf748c32008-05-06 22:41:46 +0000507 if ENABLE_USER_SITE:
508 execusercustomize()
Brett Cannon0096e262004-06-05 01:12:51 +0000509 # Remove sys.setdefaultencoding() so that users cannot change the
510 # encoding after initialization. The test for presence is needed when
511 # this module is run as a script, because this code is executed twice.
512 if hasattr(sys, "setdefaultencoding"):
513 del sys.setdefaultencoding
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000514
Brett Cannon0096e262004-06-05 01:12:51 +0000515main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000516
Christian Heimesaf748c32008-05-06 22:41:46 +0000517def _script():
518 help = """\
519 %s [--user-base] [--user-site]
520
521 Without arguments print some useful information
522 With arguments print the value of USER_BASE and/or USER_SITE separated
523 by '%s'.
524
525 Exit codes with --user-base or --user-site:
526 0 - user site directory is enabled
Christian Heimes17433d22008-05-09 12:19:09 +0000527 1 - user site directory is disabled by user
Christian Heimesaf748c32008-05-06 22:41:46 +0000528 2 - uses site directory is disabled by super user
529 or for security reasons
530 >2 - unknown error
531 """
532 args = sys.argv[1:]
533 if not args:
534 print "sys.path = ["
535 for dir in sys.path:
536 print " %r," % (dir,)
537 print "]"
538 print "USER_BASE: %r (%s)" % (USER_BASE,
539 "exists" if os.path.isdir(USER_BASE) else "doesn't exist")
540 print "USER_SITE: %r (%s)" % (USER_SITE,
541 "exists" if os.path.isdir(USER_SITE) else "doesn't exist")
542 print "ENABLE_USER_SITE: %r" % ENABLE_USER_SITE
543 sys.exit(0)
544
545 buffer = []
546 if '--user-base' in args:
547 buffer.append(USER_BASE)
548 if '--user-site' in args:
549 buffer.append(USER_SITE)
550
551 if buffer:
552 print os.pathsep.join(buffer)
553 if ENABLE_USER_SITE:
554 sys.exit(0)
555 elif ENABLE_USER_SITE is False:
556 sys.exit(1)
557 elif ENABLE_USER_SITE is None:
558 sys.exit(2)
559 else:
560 sys.exit(3)
561 else:
562 import textwrap
563 print textwrap.dedent(help % (sys.argv[0], os.pathsep))
564 sys.exit(10)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000565
566if __name__ == '__main__':
Christian Heimesaf748c32008-05-06 22:41:46 +0000567 _script()