blob: 6ef1e0bbfada59a428dd15896e76f93616a6b2c1 [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 Murrayb4ca59b2010-12-26 19:54:29 +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
Tarek Ziadé4a608c02009-08-20 21:28:05 +000065
Christian Heimes8dc226f2008-05-06 23:45:46 +000066# for distutils.commands.install
Tarek Ziadé4a608c02009-08-20 21:28:05 +000067# These values are initialized by the getuserbase() and getusersitepackages()
68# functions, through the main() function when Python starts.
Christian Heimes8dc226f2008-05-06 23:45:46 +000069USER_SITE = None
70USER_BASE = None
71
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000072
Fred Drake38cb9f12000-09-28 16:52:36 +000073def makepath(*paths):
Victor Stinnerb103a932010-10-12 22:23:23 +000074 dir = os.path.join(*paths)
75 try:
76 dir = os.path.abspath(dir)
77 except OSError:
78 pass
Fred Drake1fb5ce02001-07-02 16:55:42 +000079 return dir, os.path.normcase(dir)
Fred Drake38cb9f12000-09-28 16:52:36 +000080
Christian Heimes8dc226f2008-05-06 23:45:46 +000081
Barry Warsaw28a691b2010-04-17 00:19:56 +000082def abs_paths():
83 """Set all module __file__ and __cached__ attributes to an absolute path"""
Guido van Rossum7ac9d402007-05-18 00:24:43 +000084 for m in set(sys.modules.values()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000085 if hasattr(m, '__loader__'):
86 continue # don't mess with a PEP 302-supplied __file__
Brett Cannon0096e262004-06-05 01:12:51 +000087 try:
88 m.__file__ = os.path.abspath(m.__file__)
Victor Stinnerb103a932010-10-12 22:23:23 +000089 except (AttributeError, OSError):
Barry Warsaw28a691b2010-04-17 00:19:56 +000090 pass
91 try:
92 m.__cached__ = os.path.abspath(m.__cached__)
Victor Stinnerb103a932010-10-12 22:23:23 +000093 except (AttributeError, OSError):
Barry Warsaw28a691b2010-04-17 00:19:56 +000094 pass
Fred Drake38cb9f12000-09-28 16:52:36 +000095
Christian Heimes8dc226f2008-05-06 23:45:46 +000096
Brett Cannon0096e262004-06-05 01:12:51 +000097def removeduppaths():
98 """ Remove duplicate entries from sys.path along with making them
99 absolute"""
100 # This ensures that the initial path provided by the interpreter contains
101 # only absolute pathnames, even if we're running from the build directory.
102 L = []
103 known_paths = set()
104 for dir in sys.path:
105 # Filter out duplicate paths (on case-insensitive file systems also
106 # if they only differ in case); turn relative paths into absolute
107 # paths.
108 dir, dircase = makepath(dir)
109 if not dircase in known_paths:
110 L.append(dir)
111 known_paths.add(dircase)
112 sys.path[:] = L
113 return known_paths
Fred Drake38cb9f12000-09-28 16:52:36 +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:
Victor Stinner4e86d5b2011-05-04 13:55:36 +0200141 f = open(fullname, "r")
Brett Cannon0096e262004-06-05 01:12:51 +0000142 except IOError:
143 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000144 with f:
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000145 for n, line in enumerate(f):
Brett Cannon0096e262004-06-05 01:12:51 +0000146 if line.startswith("#"):
147 continue
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000148 try:
149 if line.startswith(("import ", "import\t")):
150 exec(line)
151 continue
152 line = line.rstrip()
153 dir, dircase = makepath(sitedir, line)
154 if not dircase in known_paths and os.path.exists(dir):
155 sys.path.append(dir)
156 known_paths.add(dircase)
Florent Xicluna54540ec2011-11-04 08:29:17 +0100157 except Exception:
R. David Murrayb4ca59b2010-12-26 19:54:29 +0000158 print("Error processing line {:d} of {}:\n".format(n+1, fullname),
159 file=sys.stderr)
160 for record in traceback.format_exception(*sys.exc_info()):
161 for line in record.splitlines():
162 print(' '+line, file=sys.stderr)
163 print("\nRemainder of file ignored", file=sys.stderr)
164 break
Brett Cannon0096e262004-06-05 01:12:51 +0000165 if reset:
166 known_paths = None
167 return known_paths
168
Christian Heimes8dc226f2008-05-06 23:45:46 +0000169
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000170def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000171 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
172 'sitedir'"""
173 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000174 known_paths = _init_pathinfo()
Brett Cannon0096e262004-06-05 01:12:51 +0000175 reset = 1
176 else:
177 reset = 0
Fred Drake1fb5ce02001-07-02 16:55:42 +0000178 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000179 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000180 sys.path.append(sitedir) # Add path component
Guido van Rossumf30bec71997-08-29 22:30:45 +0000181 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000182 names = os.listdir(sitedir)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000183 except os.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000184 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000185 names = [name for name in names if name.endswith(".pth")]
186 for name in sorted(names):
187 addpackage(sitedir, name, known_paths)
Fred Drake7f5296e2001-07-20 20:06:17 +0000188 if reset:
Brett Cannon0096e262004-06-05 01:12:51 +0000189 known_paths = None
190 return known_paths
Guido van Rossumf30bec71997-08-29 22:30:45 +0000191
Christian Heimes8dc226f2008-05-06 23:45:46 +0000192
193def check_enableusersite():
194 """Check if user site directory is safe for inclusion
195
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000196 The function tests for the command line flag (including environment var),
Christian Heimes8dc226f2008-05-06 23:45:46 +0000197 process uid/gid equal to effective uid/gid.
198
199 None: Disabled for security reasons
200 False: Disabled by user (command line option)
201 True: Safe and enabled
202 """
203 if sys.flags.no_user_site:
204 return False
205
206 if hasattr(os, "getuid") and hasattr(os, "geteuid"):
207 # check process uid == effective uid
208 if os.geteuid() != os.getuid():
209 return None
210 if hasattr(os, "getgid") and hasattr(os, "getegid"):
211 # check process gid == effective gid
212 if os.getegid() != os.getgid():
213 return None
214
215 return True
216
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000217def getuserbase():
218 """Returns the `user base` directory path.
219
220 The `user base` directory can be used to store data. If the global
221 variable ``USER_BASE`` is not initialized yet, this function will also set
222 it.
223 """
224 global USER_BASE
225 if USER_BASE is not None:
226 return USER_BASE
Tarek Ziadéedacea32010-01-29 11:41:03 +0000227 from sysconfig import get_config_var
228 USER_BASE = get_config_var('userbase')
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000229 return USER_BASE
230
231def getusersitepackages():
232 """Returns the user-specific site-packages directory path.
233
234 If the global variable ``USER_SITE`` is not initialized yet, this
235 function will also set it.
236 """
237 global USER_SITE
238 user_base = getuserbase() # this will also set USER_BASE
239
240 if USER_SITE is not None:
241 return USER_SITE
242
Tarek Ziadéedacea32010-01-29 11:41:03 +0000243 from sysconfig import get_path
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000244
245 if sys.platform == 'darwin':
246 from sysconfig import get_config_var
247 if get_config_var('PYTHONFRAMEWORK'):
248 USER_SITE = get_path('purelib', 'osx_framework_user')
249 return USER_SITE
250
Tarek Ziadéedacea32010-01-29 11:41:03 +0000251 USER_SITE = get_path('purelib', '%s_user' % os.name)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000252 return USER_SITE
Christian Heimes8dc226f2008-05-06 23:45:46 +0000253
254def addusersitepackages(known_paths):
255 """Add a per user site-package to sys.path
256
257 Each user has its own python directory with site-packages in the
258 home directory.
Christian Heimes8dc226f2008-05-06 23:45:46 +0000259 """
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000260 # get the per user site-package path
261 # this call will also make sure USER_BASE and USER_SITE are set
262 user_site = getusersitepackages()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000263
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000264 if ENABLE_USER_SITE and os.path.isdir(user_site):
265 addsitedir(user_site, known_paths)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000266 return known_paths
267
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000268def getsitepackages():
269 """Returns a list containing all global site-packages directories
270 (and possibly site-python).
Christian Heimes8dc226f2008-05-06 23:45:46 +0000271
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000272 For each directory present in the global ``PREFIXES``, this function
273 will find its `site-packages` subdirectory depending on the system
274 environment, and will return a list of full paths.
275 """
276 sitepackages = []
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000277 seen = set()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000278
279 for prefix in PREFIXES:
280 if not prefix or prefix in seen:
281 continue
Benjamin Peterson3e5cd1d2010-06-27 21:45:24 +0000282 seen.add(prefix)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000283
284 if sys.platform in ('os2emx', 'riscos'):
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000285 sitepackages.append(os.path.join(prefix, "Lib", "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000286 elif os.sep == '/':
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000287 sitepackages.append(os.path.join(prefix, "lib",
Christian Heimes8dc226f2008-05-06 23:45:46 +0000288 "python" + sys.version[:3],
289 "site-packages"))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000290 sitepackages.append(os.path.join(prefix, "lib", "site-python"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000291 else:
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000292 sitepackages.append(prefix)
293 sitepackages.append(os.path.join(prefix, "lib", "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000294 if sys.platform == "darwin":
295 # for framework builds *only* we add the standard Apple
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000296 # locations.
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000297 from sysconfig import get_config_var
298 framework = get_config_var("PYTHONFRAMEWORK")
Ronald Oussorenbda46722010-08-01 09:02:50 +0000299 if framework:
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000300 sitepackages.append(
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000301 os.path.join("/Library", framework,
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000302 sys.version[:3], "site-packages"))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000303 return sitepackages
Christian Heimes8dc226f2008-05-06 23:45:46 +0000304
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000305def addsitepackages(known_paths):
306 """Add site-packages (and possibly site-python) to sys.path"""
307 for sitedir in getsitepackages():
Christian Heimes8dc226f2008-05-06 23:45:46 +0000308 if os.path.isdir(sitedir):
309 addsitedir(sitedir, known_paths)
310
311 return known_paths
Fred Drake7f5296e2001-07-20 20:06:17 +0000312
Brett Cannon0096e262004-06-05 01:12:51 +0000313def setBEGINLIBPATH():
314 """The OS/2 EMX port has optional extension modules that do double duty
315 as DLLs (and must use the .DLL file extension) for other extensions.
316 The library search path needs to be amended so these will be found
317 during module import. Use BEGINLIBPATH so that these are at the start
318 of the library search path.
Tim Peters4e0e1b62004-07-07 20:54:48 +0000319
Brett Cannon0096e262004-06-05 01:12:51 +0000320 """
Andrew MacIntyre2e8a6e02003-12-02 12:27:25 +0000321 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
322 libpath = os.environ['BEGINLIBPATH'].split(';')
323 if libpath[-1]:
324 libpath.append(dllpath)
325 else:
326 libpath[-1] = dllpath
327 os.environ['BEGINLIBPATH'] = ';'.join(libpath)
328
329
Brett Cannon0096e262004-06-05 01:12:51 +0000330def setquit():
Brian Curtinfb1d3c12010-04-12 23:33:42 +0000331 """Define new builtins 'quit' and 'exit'.
332
333 These are objects which make the interpreter exit when called.
334 The repr of each object contains a hint at how it works.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000335
Brett Cannon0096e262004-06-05 01:12:51 +0000336 """
337 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000338 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000339 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000340 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000341 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000342 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000343
Georg Brandl24cb0532006-03-09 23:22:06 +0000344 class Quitter(object):
345 def __init__(self, name):
346 self.name = name
347 def __repr__(self):
348 return 'Use %s() or %s to exit' % (self.name, eof)
349 def __call__(self, code=None):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000350 # Shells like IDLE catch the SystemExit, but listen when their
351 # stdin wrapper is closed.
352 try:
Christian Heimes862543a2007-12-31 03:07:24 +0000353 fd = -1
354 if hasattr(sys.stdin, "fileno"):
355 fd = sys.stdin.fileno()
356 if fd != 0:
357 # Don't close stdin if it wraps fd 0
358 sys.stdin.close()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000359 except:
360 pass
Georg Brandl24cb0532006-03-09 23:22:06 +0000361 raise SystemExit(code)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000362 builtins.quit = Quitter('quit')
363 builtins.exit = Quitter('exit')
Brett Cannon0096e262004-06-05 01:12:51 +0000364
365
366class _Printer(object):
367 """interactive prompt objects for printing the license text, a list of
368 contributors and the copyright notice."""
369
Guido van Rossumd1252392000-09-05 04:39:55 +0000370 MAXLINES = 23
371
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000372 def __init__(self, name, data, files=(), dirs=()):
373 self.__name = name
374 self.__data = data
375 self.__files = files
376 self.__dirs = dirs
377 self.__lines = None
378
379 def __setup(self):
380 if self.__lines:
381 return
382 data = None
383 for dir in self.__dirs:
Brett Cannon0096e262004-06-05 01:12:51 +0000384 for filename in self.__files:
385 filename = os.path.join(dir, filename)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000386 try:
Victor Stinner4e86d5b2011-05-04 13:55:36 +0200387 fp = open(filename, "r")
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000388 data = fp.read()
389 fp.close()
390 break
391 except IOError:
392 pass
393 if data:
394 break
395 if not data:
396 data = self.__data
397 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000398 self.__linecnt = len(self.__lines)
399
400 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000401 self.__setup()
402 if len(self.__lines) <= self.MAXLINES:
403 return "\n".join(self.__lines)
404 else:
405 return "Type %s() to see the full %s text" % ((self.__name,)*2)
406
407 def __call__(self):
408 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000409 prompt = 'Hit Return for more, or q (and Return) to quit: '
410 lineno = 0
411 while 1:
412 try:
413 for i in range(lineno, lineno + self.MAXLINES):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000414 print(self.__lines[i])
Guido van Rossumd1252392000-09-05 04:39:55 +0000415 except IndexError:
416 break
417 else:
418 lineno += self.MAXLINES
419 key = None
420 while key is None:
Guido van Rossum704b34d2007-12-20 18:42:56 +0000421 key = input(prompt)
Guido van Rossumd1252392000-09-05 04:39:55 +0000422 if key not in ('', 'q'):
423 key = None
424 if key == 'q':
425 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000426
Brett Cannon0096e262004-06-05 01:12:51 +0000427def setcopyright():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000428 """Set 'copyright' and 'credits' in builtins"""
429 builtins.copyright = _Printer("copyright", sys.copyright)
Brett Cannon0096e262004-06-05 01:12:51 +0000430 if sys.platform[:4] == 'java':
Georg Brandl1a3284e2007-12-02 09:40:06 +0000431 builtins.credits = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000432 "credits",
433 "Jython is maintained by the Jython developers (www.jython.org).")
434 else:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000435 builtins.credits = _Printer("credits", """\
Brett Cannon0096e262004-06-05 01:12:51 +0000436 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
437 for supporting Python development. See www.python.org for more information.""")
438 here = os.path.dirname(os.__file__)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000439 builtins.license = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000440 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
441 ["LICENSE.txt", "LICENSE"],
442 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000443
444
Brett Cannon0096e262004-06-05 01:12:51 +0000445class _Helper(object):
Brian Curtinfb1d3c12010-04-12 23:33:42 +0000446 """Define the builtin 'help'.
Brett Cannon0096e262004-06-05 01:12:51 +0000447 This is a wrapper around pydoc.help (with a twist).
Guido van Rossum83213cc2001-06-12 16:48:52 +0000448
Brett Cannon0096e262004-06-05 01:12:51 +0000449 """
450
Guido van Rossum83213cc2001-06-12 16:48:52 +0000451 def __repr__(self):
452 return "Type help() for interactive help, " \
453 "or help(object) for help about object."
454 def __call__(self, *args, **kwds):
455 import pydoc
456 return pydoc.help(*args, **kwds)
457
Brett Cannon0096e262004-06-05 01:12:51 +0000458def sethelper():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000459 builtins.help = _Helper()
Brett Cannon0096e262004-06-05 01:12:51 +0000460
461def aliasmbcs():
462 """On Windows, some default encodings are not provided by Python,
463 while they are always available as "mbcs" in each locale. Make
464 them usable by aliasing to "mbcs" in such a case."""
465 if sys.platform == 'win32':
466 import locale, codecs
467 enc = locale.getdefaultlocale()[1]
468 if enc.startswith('cp'): # "cp***" ?
469 try:
470 codecs.lookup(enc)
471 except LookupError:
472 import encodings
473 encodings._cache[enc] = encodings._unknown
474 encodings.aliases.aliases[enc] = 'mbcs'
475
Guido van Rossum83213cc2001-06-12 16:48:52 +0000476
Brett Cannon0096e262004-06-05 01:12:51 +0000477def execsitecustomize():
478 """Run custom site specific code, if available."""
479 try:
480 import sitecustomize
481 except ImportError:
482 pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000483 except Exception as err:
Guido van Rossumc6fe9832006-08-19 00:10:28 +0000484 if os.environ.get("PYTHONVERBOSE"):
Victor Stinner52f6dd72010-03-12 14:45:56 +0000485 sys.excepthook(*sys.exc_info())
486 else:
487 sys.stderr.write(
488 "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
489 "%s: %s\n" %
490 (err.__class__.__name__, err))
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000491
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000492
Christian Heimes8dc226f2008-05-06 23:45:46 +0000493def execusercustomize():
494 """Run custom user specific code, if available."""
495 try:
496 import usercustomize
497 except ImportError:
498 pass
Victor Stinner52f6dd72010-03-12 14:45:56 +0000499 except Exception as err:
500 if os.environ.get("PYTHONVERBOSE"):
501 sys.excepthook(*sys.exc_info())
502 else:
503 sys.stderr.write(
504 "Error in usercustomize; set PYTHONVERBOSE for traceback:\n"
505 "%s: %s\n" %
506 (err.__class__.__name__, err))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000507
508
Brett Cannon0096e262004-06-05 01:12:51 +0000509def main():
Éric Araujoc09fca62011-03-23 02:06:24 +0100510 """Add standard site-specific directories to the module search path.
511
512 This function is called automatically when this module is imported,
513 unless the python interpreter was started with the -S flag.
514 """
Christian Heimes8dc226f2008-05-06 23:45:46 +0000515 global ENABLE_USER_SITE
516
Barry Warsaw28a691b2010-04-17 00:19:56 +0000517 abs_paths()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000518 known_paths = removeduppaths()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000519 if ENABLE_USER_SITE is None:
520 ENABLE_USER_SITE = check_enableusersite()
521 known_paths = addusersitepackages(known_paths)
522 known_paths = addsitepackages(known_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000523 if sys.platform == 'os2emx':
524 setBEGINLIBPATH()
525 setquit()
526 setcopyright()
527 sethelper()
528 aliasmbcs()
Brett Cannon0096e262004-06-05 01:12:51 +0000529 execsitecustomize()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000530 if ENABLE_USER_SITE:
531 execusercustomize()
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000532
Éric Araujoc09fca62011-03-23 02:06:24 +0100533# Prevent edition of sys.path when python was started with -S and
534# site is imported later.
535if not sys.flags.no_site:
536 main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000537
Christian Heimes8dc226f2008-05-06 23:45:46 +0000538def _script():
539 help = """\
540 %s [--user-base] [--user-site]
541
542 Without arguments print some useful information
543 With arguments print the value of USER_BASE and/or USER_SITE separated
544 by '%s'.
545
546 Exit codes with --user-base or --user-site:
547 0 - user site directory is enabled
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000548 1 - user site directory is disabled by user
Christian Heimes8dc226f2008-05-06 23:45:46 +0000549 2 - uses site directory is disabled by super user
550 or for security reasons
551 >2 - unknown error
552 """
553 args = sys.argv[1:]
554 if not args:
555 print("sys.path = [")
556 for dir in sys.path:
557 print(" %r," % (dir,))
558 print("]")
559 print("USER_BASE: %r (%s)" % (USER_BASE,
560 "exists" if os.path.isdir(USER_BASE) else "doesn't exist"))
561 print("USER_SITE: %r (%s)" % (USER_SITE,
562 "exists" if os.path.isdir(USER_SITE) else "doesn't exist"))
563 print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE)
564 sys.exit(0)
565
566 buffer = []
567 if '--user-base' in args:
568 buffer.append(USER_BASE)
569 if '--user-site' in args:
570 buffer.append(USER_SITE)
571
572 if buffer:
573 print(os.pathsep.join(buffer))
574 if ENABLE_USER_SITE:
575 sys.exit(0)
576 elif ENABLE_USER_SITE is False:
577 sys.exit(1)
578 elif ENABLE_USER_SITE is None:
579 sys.exit(2)
580 else:
581 sys.exit(3)
582 else:
583 import textwrap
584 print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
585 sys.exit(10)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000586
587if __name__ == '__main__':
Christian Heimes8dc226f2008-05-06 23:45:46 +0000588 _script()