blob: a0489fa461cfd6aa2b55ecf4b6a6c22b99fcaaed [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
R. David Murray6cb252f2010-12-26 22:24:54 +000058import traceback
Guido van Rossume57c96e1996-08-17 19:56:26 +000059
Christian Heimes8dc226f2008-05-06 23:45:46 +000060# Prefixes for site-packages; add additional prefixes like /usr/local here
61PREFIXES = [sys.prefix, sys.exec_prefix]
62# Enable per user site-packages directory
63# set it to False to disable the feature or True to force the feature
64ENABLE_USER_SITE = None
65# for distutils.commands.install
66USER_SITE = None
67USER_BASE = None
68
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000069
Fred Drake38cb9f12000-09-28 16:52:36 +000070def makepath(*paths):
Victor Stinner93f5cd42010-10-12 22:56:55 +000071 dir = os.path.join(*paths)
72 try:
73 dir = os.path.abspath(dir)
74 except OSError:
75 pass
Fred Drake1fb5ce02001-07-02 16:55:42 +000076 return dir, os.path.normcase(dir)
Fred Drake38cb9f12000-09-28 16:52:36 +000077
Christian Heimes8dc226f2008-05-06 23:45:46 +000078
Brett Cannon0096e262004-06-05 01:12:51 +000079def abs__file__():
80 """Set all module' __file__ attribute to an absolute path"""
Guido van Rossum7ac9d402007-05-18 00:24:43 +000081 for m in set(sys.modules.values()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000082 if hasattr(m, '__loader__'):
83 continue # don't mess with a PEP 302-supplied __file__
Brett Cannon0096e262004-06-05 01:12:51 +000084 try:
85 m.__file__ = os.path.abspath(m.__file__)
Victor Stinner93f5cd42010-10-12 22:56:55 +000086 except (AttributeError, OSError):
87 pass
Fred Drake38cb9f12000-09-28 16:52:36 +000088
Christian Heimes8dc226f2008-05-06 23:45:46 +000089
Brett Cannon0096e262004-06-05 01:12:51 +000090def removeduppaths():
91 """ Remove duplicate entries from sys.path along with making them
92 absolute"""
93 # This ensures that the initial path provided by the interpreter contains
94 # only absolute pathnames, even if we're running from the build directory.
95 L = []
96 known_paths = set()
97 for dir in sys.path:
98 # Filter out duplicate paths (on case-insensitive file systems also
99 # if they only differ in case); turn relative paths into absolute
100 # paths.
101 dir, dircase = makepath(dir)
102 if not dircase in known_paths:
103 L.append(dir)
104 known_paths.add(dircase)
105 sys.path[:] = L
106 return known_paths
Fred Drake38cb9f12000-09-28 16:52:36 +0000107
Fred Drakee80c0d32002-07-25 20:13:03 +0000108# XXX This should not be part of site.py, since it is needed even when
109# using the -S option for Python. See http://www.python.org/sf/586680
Brett Cannon0096e262004-06-05 01:12:51 +0000110def addbuilddir():
111 """Append ./build/lib.<platform> in case we're running in the build dir
112 (especially for Guido :-)"""
Jeremy Hylton6d58bf62003-07-18 17:45:33 +0000113 from distutils.util import get_platform
114 s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
Christian Heimes1af737c2008-01-23 08:24:23 +0000115 if hasattr(sys, 'gettotalrefcount'):
116 s += '-pydebug'
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000117 s = os.path.join(os.path.dirname(sys.path[-1]), s)
118 sys.path.append(s)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000119
Christian Heimes8dc226f2008-05-06 23:45:46 +0000120
Fred Drake7f5296e2001-07-20 20:06:17 +0000121def _init_pathinfo():
Brett Cannon0096e262004-06-05 01:12:51 +0000122 """Return a set containing all existing directory entries from sys.path"""
123 d = set()
Fred Drake7f5296e2001-07-20 20:06:17 +0000124 for dir in sys.path:
Brett Cannon0096e262004-06-05 01:12:51 +0000125 try:
126 if os.path.isdir(dir):
127 dir, dircase = makepath(dir)
128 d.add(dircase)
129 except TypeError:
Fred Drake7f5296e2001-07-20 20:06:17 +0000130 continue
Brett Cannon0096e262004-06-05 01:12:51 +0000131 return d
Fred Drake7f5296e2001-07-20 20:06:17 +0000132
Christian Heimes8dc226f2008-05-06 23:45:46 +0000133
Brett Cannon0096e262004-06-05 01:12:51 +0000134def addpackage(sitedir, name, known_paths):
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000135 """Process a .pth file within the site-packages directory:
136 For each line in the file, either combine it with sitedir to a path
137 and add that to known_paths, or execute it if it starts with 'import '.
138 """
Brett Cannon0096e262004-06-05 01:12:51 +0000139 if known_paths is None:
Fred Drake7f5296e2001-07-20 20:06:17 +0000140 _init_pathinfo()
141 reset = 1
142 else:
143 reset = 0
Brett Cannon0096e262004-06-05 01:12:51 +0000144 fullname = os.path.join(sitedir, name)
145 try:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000146 f = open(fullname, "rU")
Brett Cannon0096e262004-06-05 01:12:51 +0000147 except IOError:
148 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000149 with f:
R. David Murray6cb252f2010-12-26 22:24:54 +0000150 for n, line in enumerate(f):
Brett Cannon0096e262004-06-05 01:12:51 +0000151 if line.startswith("#"):
152 continue
R. David Murray6cb252f2010-12-26 22:24:54 +0000153 try:
154 if line.startswith(("import ", "import\t")):
155 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)
162 except Exception as err:
163 print("Error processing line {:d} of {}:\n".format(n+1, fullname),
164 file=sys.stderr)
165 for record in traceback.format_exception(*sys.exc_info()):
166 for line in record.splitlines():
167 print(' '+line, file=sys.stderr)
168 print("\nRemainder of file ignored", file=sys.stderr)
169 break
Brett Cannon0096e262004-06-05 01:12:51 +0000170 if reset:
171 known_paths = None
172 return known_paths
173
Christian Heimes8dc226f2008-05-06 23:45:46 +0000174
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000175def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000176 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
177 'sitedir'"""
178 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000179 known_paths = _init_pathinfo()
Brett Cannon0096e262004-06-05 01:12:51 +0000180 reset = 1
181 else:
182 reset = 0
Fred Drake1fb5ce02001-07-02 16:55:42 +0000183 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000184 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000185 sys.path.append(sitedir) # Add path component
Guido van Rossumf30bec71997-08-29 22:30:45 +0000186 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000187 names = os.listdir(sitedir)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000188 except os.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000189 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000190 names = [name for name in names if name.endswith(".pth")]
191 for name in sorted(names):
192 addpackage(sitedir, name, known_paths)
Fred Drake7f5296e2001-07-20 20:06:17 +0000193 if reset:
Brett Cannon0096e262004-06-05 01:12:51 +0000194 known_paths = None
195 return known_paths
Guido van Rossumf30bec71997-08-29 22:30:45 +0000196
Christian Heimes8dc226f2008-05-06 23:45:46 +0000197
198def check_enableusersite():
199 """Check if user site directory is safe for inclusion
200
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000201 The function tests for the command line flag (including environment var),
Christian Heimes8dc226f2008-05-06 23:45:46 +0000202 process uid/gid equal to effective uid/gid.
203
204 None: Disabled for security reasons
205 False: Disabled by user (command line option)
206 True: Safe and enabled
207 """
208 if sys.flags.no_user_site:
209 return False
210
211 if hasattr(os, "getuid") and hasattr(os, "geteuid"):
212 # check process uid == effective uid
213 if os.geteuid() != os.getuid():
214 return None
215 if hasattr(os, "getgid") and hasattr(os, "getegid"):
216 # check process gid == effective gid
217 if os.getegid() != os.getgid():
218 return None
219
220 return True
221
222
223def addusersitepackages(known_paths):
224 """Add a per user site-package to sys.path
225
226 Each user has its own python directory with site-packages in the
227 home directory.
228
229 USER_BASE is the root directory for all Python versions
230
231 USER_SITE is the user specific site-packages directory
232
233 USER_SITE/.. can be used for data.
234 """
235 global USER_BASE, USER_SITE, ENABLE_USER_SITE
236 env_base = os.environ.get("PYTHONUSERBASE", None)
237
238 def joinuser(*args):
239 return os.path.expanduser(os.path.join(*args))
240
241 #if sys.platform in ('os2emx', 'riscos'):
242 # # Don't know what to put here
243 # USER_BASE = ''
244 # USER_SITE = ''
245 if os.name == "nt":
246 base = os.environ.get("APPDATA") or "~"
247 USER_BASE = env_base if env_base else joinuser(base, "Python")
248 USER_SITE = os.path.join(USER_BASE,
249 "Python" + sys.version[0] + sys.version[2],
250 "site-packages")
251 else:
252 USER_BASE = env_base if env_base else joinuser("~", ".local")
253 USER_SITE = os.path.join(USER_BASE, "lib",
254 "python" + sys.version[:3],
255 "site-packages")
256
257 if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
258 addsitedir(USER_SITE, known_paths)
259 return known_paths
260
261
Brett Cannon0096e262004-06-05 01:12:51 +0000262def addsitepackages(known_paths):
263 """Add site-packages (and possibly site-python) to sys.path"""
Christian Heimes8dc226f2008-05-06 23:45:46 +0000264 sitedirs = []
265 seen = []
266
267 for prefix in PREFIXES:
268 if not prefix or prefix in seen:
269 continue
270 seen.append(prefix)
271
272 if sys.platform in ('os2emx', 'riscos'):
273 sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
274 elif os.sep == '/':
275 sitedirs.append(os.path.join(prefix, "lib",
276 "python" + sys.version[:3],
277 "site-packages"))
278 sitedirs.append(os.path.join(prefix, "lib", "site-python"))
279 else:
280 sitedirs.append(prefix)
281 sitedirs.append(os.path.join(prefix, "lib", "site-packages"))
282
283 if sys.platform == "darwin":
284 # for framework builds *only* we add the standard Apple
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000285 # locations.
Christian Heimes8dc226f2008-05-06 23:45:46 +0000286 if 'Python.framework' in prefix:
287 sitedirs.append(
288 os.path.expanduser(
289 os.path.join("~", "Library", "Python",
290 sys.version[:3], "site-packages")))
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000291 sitedirs.append(
292 os.path.join("/Library", "Python",
293 sys.version[:3], "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000294
295 for sitedir in sitedirs:
296 if os.path.isdir(sitedir):
297 addsitedir(sitedir, known_paths)
298
299 return known_paths
Fred Drake7f5296e2001-07-20 20:06:17 +0000300
Fred Drake1fb5ce02001-07-02 16:55:42 +0000301
Brett Cannon0096e262004-06-05 01:12:51 +0000302def setBEGINLIBPATH():
303 """The OS/2 EMX port has optional extension modules that do double duty
304 as DLLs (and must use the .DLL file extension) for other extensions.
305 The library search path needs to be amended so these will be found
306 during module import. Use BEGINLIBPATH so that these are at the start
307 of the library search path.
Tim Peters4e0e1b62004-07-07 20:54:48 +0000308
Brett Cannon0096e262004-06-05 01:12:51 +0000309 """
Andrew MacIntyre2e8a6e02003-12-02 12:27:25 +0000310 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
311 libpath = os.environ['BEGINLIBPATH'].split(';')
312 if libpath[-1]:
313 libpath.append(dllpath)
314 else:
315 libpath[-1] = dllpath
316 os.environ['BEGINLIBPATH'] = ';'.join(libpath)
317
318
Brett Cannon0096e262004-06-05 01:12:51 +0000319def setquit():
320 """Define new built-ins 'quit' and 'exit'.
321 These are simply strings that display a hint on how to exit.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000322
Brett Cannon0096e262004-06-05 01:12:51 +0000323 """
324 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000325 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000326 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000327 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000328 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000329 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000330
Georg Brandl24cb0532006-03-09 23:22:06 +0000331 class Quitter(object):
332 def __init__(self, name):
333 self.name = name
334 def __repr__(self):
335 return 'Use %s() or %s to exit' % (self.name, eof)
336 def __call__(self, code=None):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000337 # Shells like IDLE catch the SystemExit, but listen when their
338 # stdin wrapper is closed.
339 try:
Christian Heimes862543a2007-12-31 03:07:24 +0000340 fd = -1
341 if hasattr(sys.stdin, "fileno"):
342 fd = sys.stdin.fileno()
343 if fd != 0:
344 # Don't close stdin if it wraps fd 0
345 sys.stdin.close()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000346 except:
347 pass
Georg Brandl24cb0532006-03-09 23:22:06 +0000348 raise SystemExit(code)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000349 builtins.quit = Quitter('quit')
350 builtins.exit = Quitter('exit')
Brett Cannon0096e262004-06-05 01:12:51 +0000351
352
353class _Printer(object):
354 """interactive prompt objects for printing the license text, a list of
355 contributors and the copyright notice."""
356
Guido van Rossumd1252392000-09-05 04:39:55 +0000357 MAXLINES = 23
358
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000359 def __init__(self, name, data, files=(), dirs=()):
360 self.__name = name
361 self.__data = data
362 self.__files = files
363 self.__dirs = dirs
364 self.__lines = None
365
366 def __setup(self):
367 if self.__lines:
368 return
369 data = None
370 for dir in self.__dirs:
Brett Cannon0096e262004-06-05 01:12:51 +0000371 for filename in self.__files:
372 filename = os.path.join(dir, filename)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000373 try:
Alex Martelli01c77c62006-08-24 02:58:11 +0000374 fp = open(filename, "rU")
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000375 data = fp.read()
376 fp.close()
377 break
378 except IOError:
379 pass
380 if data:
381 break
382 if not data:
383 data = self.__data
384 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000385 self.__linecnt = len(self.__lines)
386
387 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000388 self.__setup()
389 if len(self.__lines) <= self.MAXLINES:
390 return "\n".join(self.__lines)
391 else:
392 return "Type %s() to see the full %s text" % ((self.__name,)*2)
393
394 def __call__(self):
395 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000396 prompt = 'Hit Return for more, or q (and Return) to quit: '
397 lineno = 0
398 while 1:
399 try:
400 for i in range(lineno, lineno + self.MAXLINES):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000401 print(self.__lines[i])
Guido van Rossumd1252392000-09-05 04:39:55 +0000402 except IndexError:
403 break
404 else:
405 lineno += self.MAXLINES
406 key = None
407 while key is None:
Guido van Rossum704b34d2007-12-20 18:42:56 +0000408 key = input(prompt)
Guido van Rossumd1252392000-09-05 04:39:55 +0000409 if key not in ('', 'q'):
410 key = None
411 if key == 'q':
412 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000413
Brett Cannon0096e262004-06-05 01:12:51 +0000414def setcopyright():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000415 """Set 'copyright' and 'credits' in builtins"""
416 builtins.copyright = _Printer("copyright", sys.copyright)
Brett Cannon0096e262004-06-05 01:12:51 +0000417 if sys.platform[:4] == 'java':
Georg Brandl1a3284e2007-12-02 09:40:06 +0000418 builtins.credits = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000419 "credits",
420 "Jython is maintained by the Jython developers (www.jython.org).")
421 else:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000422 builtins.credits = _Printer("credits", """\
Brett Cannon0096e262004-06-05 01:12:51 +0000423 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
424 for supporting Python development. See www.python.org for more information.""")
425 here = os.path.dirname(os.__file__)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000426 builtins.license = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000427 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
428 ["LICENSE.txt", "LICENSE"],
429 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000430
431
Brett Cannon0096e262004-06-05 01:12:51 +0000432class _Helper(object):
433 """Define the built-in 'help'.
434 This is a wrapper around pydoc.help (with a twist).
Guido van Rossum83213cc2001-06-12 16:48:52 +0000435
Brett Cannon0096e262004-06-05 01:12:51 +0000436 """
437
Guido van Rossum83213cc2001-06-12 16:48:52 +0000438 def __repr__(self):
439 return "Type help() for interactive help, " \
440 "or help(object) for help about object."
441 def __call__(self, *args, **kwds):
442 import pydoc
443 return pydoc.help(*args, **kwds)
444
Brett Cannon0096e262004-06-05 01:12:51 +0000445def sethelper():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000446 builtins.help = _Helper()
Brett Cannon0096e262004-06-05 01:12:51 +0000447
448def aliasmbcs():
449 """On Windows, some default encodings are not provided by Python,
450 while they are always available as "mbcs" in each locale. Make
451 them usable by aliasing to "mbcs" in such a case."""
452 if sys.platform == 'win32':
453 import locale, codecs
454 enc = locale.getdefaultlocale()[1]
455 if enc.startswith('cp'): # "cp***" ?
456 try:
457 codecs.lookup(enc)
458 except LookupError:
459 import encodings
460 encodings._cache[enc] = encodings._unknown
461 encodings.aliases.aliases[enc] = 'mbcs'
462
463def setencoding():
464 """Set the string encoding used by the Unicode implementation. The
465 default is 'ascii', but if you're willing to experiment, you can
466 change this."""
467 encoding = "ascii" # Default value set by _PyUnicode_Init()
468 if 0:
469 # Enable to support locale aware default string encodings.
470 import locale
471 loc = locale.getdefaultlocale()
472 if loc[1]:
473 encoding = loc[1]
474 if 0:
475 # Enable to switch off string to Unicode coercion and implicit
476 # Unicode to string conversion.
477 encoding = "undefined"
478 if encoding != "ascii":
479 # On Non-Unicode builds this will raise an AttributeError...
480 sys.setdefaultencoding(encoding) # Needs Python Unicode build !
Guido van Rossum83213cc2001-06-12 16:48:52 +0000481
482
Brett Cannon0096e262004-06-05 01:12:51 +0000483def execsitecustomize():
484 """Run custom site specific code, if available."""
485 try:
486 import sitecustomize
487 except ImportError:
488 pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000489 except Exception as err:
Guido van Rossumc6fe9832006-08-19 00:10:28 +0000490 if os.environ.get("PYTHONVERBOSE"):
Victor Stinnerffbc2f62010-03-21 21:48:45 +0000491 sys.excepthook(*sys.exc_info())
492 else:
493 sys.stderr.write(
494 "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
495 "%s: %s\n" %
496 (err.__class__.__name__, err))
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000497
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000498
Christian Heimes8dc226f2008-05-06 23:45:46 +0000499def execusercustomize():
500 """Run custom user specific code, if available."""
501 try:
502 import usercustomize
503 except ImportError:
504 pass
Victor Stinnerffbc2f62010-03-21 21:48:45 +0000505 except Exception as err:
506 if os.environ.get("PYTHONVERBOSE"):
507 sys.excepthook(*sys.exc_info())
508 else:
509 sys.stderr.write(
510 "Error in usercustomize; set PYTHONVERBOSE for traceback:\n"
511 "%s: %s\n" %
512 (err.__class__.__name__, err))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000513
514
Brett Cannon0096e262004-06-05 01:12:51 +0000515def main():
Christian Heimes8dc226f2008-05-06 23:45:46 +0000516 global ENABLE_USER_SITE
517
Brett Cannon0096e262004-06-05 01:12:51 +0000518 abs__file__()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000519 known_paths = removeduppaths()
Brett Cannon0096e262004-06-05 01:12:51 +0000520 if (os.name == "posix" and sys.path and
521 os.path.basename(sys.path[-1]) == "Modules"):
522 addbuilddir()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000523 if ENABLE_USER_SITE is None:
524 ENABLE_USER_SITE = check_enableusersite()
525 known_paths = addusersitepackages(known_paths)
526 known_paths = addsitepackages(known_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000527 if sys.platform == 'os2emx':
528 setBEGINLIBPATH()
529 setquit()
530 setcopyright()
531 sethelper()
532 aliasmbcs()
533 setencoding()
534 execsitecustomize()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000535 if ENABLE_USER_SITE:
536 execusercustomize()
Brett Cannon0096e262004-06-05 01:12:51 +0000537 # Remove sys.setdefaultencoding() so that users cannot change the
538 # encoding after initialization. The test for presence is needed when
539 # this module is run as a script, because this code is executed twice.
540 if hasattr(sys, "setdefaultencoding"):
541 del sys.setdefaultencoding
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000542
Brett Cannon0096e262004-06-05 01:12:51 +0000543main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000544
Christian Heimes8dc226f2008-05-06 23:45:46 +0000545def _script():
546 help = """\
547 %s [--user-base] [--user-site]
548
549 Without arguments print some useful information
550 With arguments print the value of USER_BASE and/or USER_SITE separated
551 by '%s'.
552
553 Exit codes with --user-base or --user-site:
554 0 - user site directory is enabled
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000555 1 - user site directory is disabled by user
Christian Heimes8dc226f2008-05-06 23:45:46 +0000556 2 - uses site directory is disabled by super user
557 or for security reasons
558 >2 - unknown error
559 """
560 args = sys.argv[1:]
561 if not args:
562 print("sys.path = [")
563 for dir in sys.path:
564 print(" %r," % (dir,))
565 print("]")
566 print("USER_BASE: %r (%s)" % (USER_BASE,
567 "exists" if os.path.isdir(USER_BASE) else "doesn't exist"))
568 print("USER_SITE: %r (%s)" % (USER_SITE,
569 "exists" if os.path.isdir(USER_SITE) else "doesn't exist"))
570 print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE)
571 sys.exit(0)
572
573 buffer = []
574 if '--user-base' in args:
575 buffer.append(USER_BASE)
576 if '--user-site' in args:
577 buffer.append(USER_SITE)
578
579 if buffer:
580 print(os.pathsep.join(buffer))
581 if ENABLE_USER_SITE:
582 sys.exit(0)
583 elif ENABLE_USER_SITE is False:
584 sys.exit(1)
585 elif ENABLE_USER_SITE is None:
586 sys.exit(2)
587 else:
588 sys.exit(3)
589 else:
590 import textwrap
591 print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
592 sys.exit(10)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000593
594if __name__ == '__main__':
Christian Heimes8dc226f2008-05-06 23:45:46 +0000595 _script()