blob: 8563df2464521d1ec419aee3a634f127e9021f38 [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
Tarek Ziadé4a608c02009-08-20 21:28:05 +000064
Christian Heimes8dc226f2008-05-06 23:45:46 +000065# for distutils.commands.install
Tarek Ziadé4a608c02009-08-20 21:28:05 +000066# These values are initialized by the getuserbase() and getusersitepackages()
67# functions, through the main() function when Python starts.
Christian Heimes8dc226f2008-05-06 23:45:46 +000068USER_SITE = None
69USER_BASE = None
70
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000071
Fred Drake38cb9f12000-09-28 16:52:36 +000072def makepath(*paths):
Fred Drake1fb5ce02001-07-02 16:55:42 +000073 dir = os.path.abspath(os.path.join(*paths))
74 return dir, os.path.normcase(dir)
Fred Drake38cb9f12000-09-28 16:52:36 +000075
Christian Heimes8dc226f2008-05-06 23:45:46 +000076
Barry Warsaw28a691b2010-04-17 00:19:56 +000077def abs_paths():
78 """Set all module __file__ and __cached__ attributes to an absolute path"""
Guido van Rossum7ac9d402007-05-18 00:24:43 +000079 for m in set(sys.modules.values()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000080 if hasattr(m, '__loader__'):
81 continue # don't mess with a PEP 302-supplied __file__
Brett Cannon0096e262004-06-05 01:12:51 +000082 try:
83 m.__file__ = os.path.abspath(m.__file__)
84 except AttributeError:
Barry Warsaw28a691b2010-04-17 00:19:56 +000085 pass
86 try:
87 m.__cached__ = os.path.abspath(m.__cached__)
88 except AttributeError:
89 pass
Fred Drake38cb9f12000-09-28 16:52:36 +000090
Christian Heimes8dc226f2008-05-06 23:45:46 +000091
Brett Cannon0096e262004-06-05 01:12:51 +000092def removeduppaths():
93 """ Remove duplicate entries from sys.path along with making them
94 absolute"""
95 # This ensures that the initial path provided by the interpreter contains
96 # only absolute pathnames, even if we're running from the build directory.
97 L = []
98 known_paths = set()
99 for dir in sys.path:
100 # Filter out duplicate paths (on case-insensitive file systems also
101 # if they only differ in case); turn relative paths into absolute
102 # paths.
103 dir, dircase = makepath(dir)
104 if not dircase in known_paths:
105 L.append(dir)
106 known_paths.add(dircase)
107 sys.path[:] = L
108 return known_paths
Fred Drake38cb9f12000-09-28 16:52:36 +0000109
Fred Drakee80c0d32002-07-25 20:13:03 +0000110# XXX This should not be part of site.py, since it is needed even when
111# using the -S option for Python. See http://www.python.org/sf/586680
Brett Cannon0096e262004-06-05 01:12:51 +0000112def addbuilddir():
113 """Append ./build/lib.<platform> in case we're running in the build dir
114 (especially for Guido :-)"""
Tarek Ziadéedacea32010-01-29 11:41:03 +0000115 from sysconfig import get_platform
Jeremy Hylton6d58bf62003-07-18 17:45:33 +0000116 s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
Christian Heimes1af737c2008-01-23 08:24:23 +0000117 if hasattr(sys, 'gettotalrefcount'):
118 s += '-pydebug'
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000119 s = os.path.join(os.path.dirname(sys.path.pop()), s)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000120 sys.path.append(s)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000121
Christian Heimes8dc226f2008-05-06 23:45:46 +0000122
Fred Drake7f5296e2001-07-20 20:06:17 +0000123def _init_pathinfo():
Brett Cannon0096e262004-06-05 01:12:51 +0000124 """Return a set containing all existing directory entries from sys.path"""
125 d = set()
Fred Drake7f5296e2001-07-20 20:06:17 +0000126 for dir in sys.path:
Brett Cannon0096e262004-06-05 01:12:51 +0000127 try:
128 if os.path.isdir(dir):
129 dir, dircase = makepath(dir)
130 d.add(dircase)
131 except TypeError:
Fred Drake7f5296e2001-07-20 20:06:17 +0000132 continue
Brett Cannon0096e262004-06-05 01:12:51 +0000133 return d
Fred Drake7f5296e2001-07-20 20:06:17 +0000134
Christian Heimes8dc226f2008-05-06 23:45:46 +0000135
Brett Cannon0096e262004-06-05 01:12:51 +0000136def addpackage(sitedir, name, known_paths):
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000137 """Process a .pth file within the site-packages directory:
138 For each line in the file, either combine it with sitedir to a path
139 and add that to known_paths, or execute it if it starts with 'import '.
140 """
Brett Cannon0096e262004-06-05 01:12:51 +0000141 if known_paths is None:
Fred Drake7f5296e2001-07-20 20:06:17 +0000142 _init_pathinfo()
143 reset = 1
144 else:
145 reset = 0
Brett Cannon0096e262004-06-05 01:12:51 +0000146 fullname = os.path.join(sitedir, name)
147 try:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000148 f = open(fullname, "rU")
Brett Cannon0096e262004-06-05 01:12:51 +0000149 except IOError:
150 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000151 with f:
Brett Cannon0096e262004-06-05 01:12:51 +0000152 for line in f:
153 if line.startswith("#"):
154 continue
Christian Heimes8dc226f2008-05-06 23:45:46 +0000155 if line.startswith(("import ", "import\t")):
Georg Brandl7cae87c2006-09-06 06:51:57 +0000156 exec(line)
Brett Cannon0096e262004-06-05 01:12:51 +0000157 continue
158 line = line.rstrip()
159 dir, dircase = makepath(sitedir, line)
160 if not dircase in known_paths and os.path.exists(dir):
161 sys.path.append(dir)
162 known_paths.add(dircase)
Brett Cannon0096e262004-06-05 01:12:51 +0000163 if reset:
164 known_paths = None
165 return known_paths
166
Christian Heimes8dc226f2008-05-06 23:45:46 +0000167
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000168def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000169 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
170 'sitedir'"""
171 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000172 known_paths = _init_pathinfo()
Brett Cannon0096e262004-06-05 01:12:51 +0000173 reset = 1
174 else:
175 reset = 0
Fred Drake1fb5ce02001-07-02 16:55:42 +0000176 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000177 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000178 sys.path.append(sitedir) # Add path component
Guido van Rossumf30bec71997-08-29 22:30:45 +0000179 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000180 names = os.listdir(sitedir)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000181 except os.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000182 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000183 names = [name for name in names if name.endswith(".pth")]
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 Heimes8dc226f2008-05-06 23:45:46 +0000190
191def check_enableusersite():
192 """Check if user site directory is safe for inclusion
193
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000194 The function tests for the command line flag (including environment var),
Christian Heimes8dc226f2008-05-06 23:45: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
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000215def getuserbase():
216 """Returns the `user base` directory path.
217
218 The `user base` directory can be used to store data. If the global
219 variable ``USER_BASE`` is not initialized yet, this function will also set
220 it.
221 """
222 global USER_BASE
223 if USER_BASE is not None:
224 return USER_BASE
Tarek Ziadéedacea32010-01-29 11:41:03 +0000225 from sysconfig import get_config_var
226 USER_BASE = get_config_var('userbase')
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000227 return USER_BASE
228
229def getusersitepackages():
230 """Returns the user-specific site-packages directory path.
231
232 If the global variable ``USER_SITE`` is not initialized yet, this
233 function will also set it.
234 """
235 global USER_SITE
236 user_base = getuserbase() # this will also set USER_BASE
237
238 if USER_SITE is not None:
239 return USER_SITE
240
Tarek Ziadéedacea32010-01-29 11:41:03 +0000241 from sysconfig import get_path
242 import os
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000243
244 if sys.platform == 'darwin':
245 from sysconfig import get_config_var
246 if get_config_var('PYTHONFRAMEWORK'):
247 USER_SITE = get_path('purelib', 'osx_framework_user')
248 return USER_SITE
249
Tarek Ziadéedacea32010-01-29 11:41:03 +0000250 USER_SITE = get_path('purelib', '%s_user' % os.name)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000251 return USER_SITE
Christian Heimes8dc226f2008-05-06 23:45:46 +0000252
253def addusersitepackages(known_paths):
254 """Add a per user site-package to sys.path
255
256 Each user has its own python directory with site-packages in the
257 home directory.
Christian Heimes8dc226f2008-05-06 23:45:46 +0000258 """
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000259 # get the per user site-package path
260 # this call will also make sure USER_BASE and USER_SITE are set
261 user_site = getusersitepackages()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000262
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000263 if ENABLE_USER_SITE and os.path.isdir(user_site):
264 addsitedir(user_site, known_paths)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000265 return known_paths
266
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000267def getsitepackages():
268 """Returns a list containing all global site-packages directories
269 (and possibly site-python).
Christian Heimes8dc226f2008-05-06 23:45:46 +0000270
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000271 For each directory present in the global ``PREFIXES``, this function
272 will find its `site-packages` subdirectory depending on the system
273 environment, and will return a list of full paths.
274 """
275 sitepackages = []
Christian Heimes8dc226f2008-05-06 23:45:46 +0000276 seen = []
277
278 for prefix in PREFIXES:
279 if not prefix or prefix in seen:
280 continue
281 seen.append(prefix)
282
283 if sys.platform in ('os2emx', 'riscos'):
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000284 sitepackages.append(os.path.join(prefix, "Lib", "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000285 elif os.sep == '/':
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000286 sitepackages.append(os.path.join(prefix, "lib",
Christian Heimes8dc226f2008-05-06 23:45:46 +0000287 "python" + sys.version[:3],
288 "site-packages"))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000289 sitepackages.append(os.path.join(prefix, "lib", "site-python"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000290 else:
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000291 sitepackages.append(prefix)
292 sitepackages.append(os.path.join(prefix, "lib", "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000293 if sys.platform == "darwin":
294 # for framework builds *only* we add the standard Apple
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000295 # locations.
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000296 from sysconfig import get_config_var
297 framework = get_config_var("PYTHONFRAMEWORK")
298 if framework and "/%s.framework/"%(framework,) in prefix:
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000299 sitepackages.append(
Ronald Oussoren4cda46a2010-05-08 10:49:43 +0000300 os.path.join("/Library", framework,
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000301 sys.version[:3], "site-packages"))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000302 return sitepackages
Christian Heimes8dc226f2008-05-06 23:45:46 +0000303
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000304def addsitepackages(known_paths):
305 """Add site-packages (and possibly site-python) to sys.path"""
306 for sitedir in getsitepackages():
Christian Heimes8dc226f2008-05-06 23:45:46 +0000307 if os.path.isdir(sitedir):
308 addsitedir(sitedir, known_paths)
309
310 return known_paths
Fred Drake7f5296e2001-07-20 20:06:17 +0000311
Brett Cannon0096e262004-06-05 01:12:51 +0000312def setBEGINLIBPATH():
313 """The OS/2 EMX port has optional extension modules that do double duty
314 as DLLs (and must use the .DLL file extension) for other extensions.
315 The library search path needs to be amended so these will be found
316 during module import. Use BEGINLIBPATH so that these are at the start
317 of the library search path.
Tim Peters4e0e1b62004-07-07 20:54:48 +0000318
Brett Cannon0096e262004-06-05 01:12:51 +0000319 """
Andrew MacIntyre2e8a6e02003-12-02 12:27:25 +0000320 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
321 libpath = os.environ['BEGINLIBPATH'].split(';')
322 if libpath[-1]:
323 libpath.append(dllpath)
324 else:
325 libpath[-1] = dllpath
326 os.environ['BEGINLIBPATH'] = ';'.join(libpath)
327
328
Brett Cannon0096e262004-06-05 01:12:51 +0000329def setquit():
Brian Curtinfb1d3c12010-04-12 23:33:42 +0000330 """Define new builtins 'quit' and 'exit'.
331
332 These are objects which make the interpreter exit when called.
333 The repr of each object contains a hint at how it works.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000334
Brett Cannon0096e262004-06-05 01:12:51 +0000335 """
336 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000337 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000338 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000339 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000340 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000341 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000342
Georg Brandl24cb0532006-03-09 23:22:06 +0000343 class Quitter(object):
344 def __init__(self, name):
345 self.name = name
346 def __repr__(self):
347 return 'Use %s() or %s to exit' % (self.name, eof)
348 def __call__(self, code=None):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000349 # Shells like IDLE catch the SystemExit, but listen when their
350 # stdin wrapper is closed.
351 try:
Christian Heimes862543a2007-12-31 03:07:24 +0000352 fd = -1
353 if hasattr(sys.stdin, "fileno"):
354 fd = sys.stdin.fileno()
355 if fd != 0:
356 # Don't close stdin if it wraps fd 0
357 sys.stdin.close()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000358 except:
359 pass
Georg Brandl24cb0532006-03-09 23:22:06 +0000360 raise SystemExit(code)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000361 builtins.quit = Quitter('quit')
362 builtins.exit = Quitter('exit')
Brett Cannon0096e262004-06-05 01:12:51 +0000363
364
365class _Printer(object):
366 """interactive prompt objects for printing the license text, a list of
367 contributors and the copyright notice."""
368
Guido van Rossumd1252392000-09-05 04:39:55 +0000369 MAXLINES = 23
370
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000371 def __init__(self, name, data, files=(), dirs=()):
372 self.__name = name
373 self.__data = data
374 self.__files = files
375 self.__dirs = dirs
376 self.__lines = None
377
378 def __setup(self):
379 if self.__lines:
380 return
381 data = None
382 for dir in self.__dirs:
Brett Cannon0096e262004-06-05 01:12:51 +0000383 for filename in self.__files:
384 filename = os.path.join(dir, filename)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000385 try:
Alex Martelli01c77c62006-08-24 02:58:11 +0000386 fp = open(filename, "rU")
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000387 data = fp.read()
388 fp.close()
389 break
390 except IOError:
391 pass
392 if data:
393 break
394 if not data:
395 data = self.__data
396 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000397 self.__linecnt = len(self.__lines)
398
399 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000400 self.__setup()
401 if len(self.__lines) <= self.MAXLINES:
402 return "\n".join(self.__lines)
403 else:
404 return "Type %s() to see the full %s text" % ((self.__name,)*2)
405
406 def __call__(self):
407 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000408 prompt = 'Hit Return for more, or q (and Return) to quit: '
409 lineno = 0
410 while 1:
411 try:
412 for i in range(lineno, lineno + self.MAXLINES):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000413 print(self.__lines[i])
Guido van Rossumd1252392000-09-05 04:39:55 +0000414 except IndexError:
415 break
416 else:
417 lineno += self.MAXLINES
418 key = None
419 while key is None:
Guido van Rossum704b34d2007-12-20 18:42:56 +0000420 key = input(prompt)
Guido van Rossumd1252392000-09-05 04:39:55 +0000421 if key not in ('', 'q'):
422 key = None
423 if key == 'q':
424 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000425
Brett Cannon0096e262004-06-05 01:12:51 +0000426def setcopyright():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000427 """Set 'copyright' and 'credits' in builtins"""
428 builtins.copyright = _Printer("copyright", sys.copyright)
Brett Cannon0096e262004-06-05 01:12:51 +0000429 if sys.platform[:4] == 'java':
Georg Brandl1a3284e2007-12-02 09:40:06 +0000430 builtins.credits = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000431 "credits",
432 "Jython is maintained by the Jython developers (www.jython.org).")
433 else:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000434 builtins.credits = _Printer("credits", """\
Brett Cannon0096e262004-06-05 01:12:51 +0000435 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
436 for supporting Python development. See www.python.org for more information.""")
437 here = os.path.dirname(os.__file__)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000438 builtins.license = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000439 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
440 ["LICENSE.txt", "LICENSE"],
441 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000442
443
Brett Cannon0096e262004-06-05 01:12:51 +0000444class _Helper(object):
Brian Curtinfb1d3c12010-04-12 23:33:42 +0000445 """Define the builtin 'help'.
Brett Cannon0096e262004-06-05 01:12:51 +0000446 This is a wrapper around pydoc.help (with a twist).
Guido van Rossum83213cc2001-06-12 16:48:52 +0000447
Brett Cannon0096e262004-06-05 01:12:51 +0000448 """
449
Guido van Rossum83213cc2001-06-12 16:48:52 +0000450 def __repr__(self):
451 return "Type help() for interactive help, " \
452 "or help(object) for help about object."
453 def __call__(self, *args, **kwds):
454 import pydoc
455 return pydoc.help(*args, **kwds)
456
Brett Cannon0096e262004-06-05 01:12:51 +0000457def sethelper():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000458 builtins.help = _Helper()
Brett Cannon0096e262004-06-05 01:12:51 +0000459
460def aliasmbcs():
461 """On Windows, some default encodings are not provided by Python,
462 while they are always available as "mbcs" in each locale. Make
463 them usable by aliasing to "mbcs" in such a case."""
464 if sys.platform == 'win32':
465 import locale, codecs
466 enc = locale.getdefaultlocale()[1]
467 if enc.startswith('cp'): # "cp***" ?
468 try:
469 codecs.lookup(enc)
470 except LookupError:
471 import encodings
472 encodings._cache[enc] = encodings._unknown
473 encodings.aliases.aliases[enc] = 'mbcs'
474
475def setencoding():
476 """Set the string encoding used by the Unicode implementation. The
477 default is 'ascii', but if you're willing to experiment, you can
478 change this."""
479 encoding = "ascii" # Default value set by _PyUnicode_Init()
480 if 0:
481 # Enable to support locale aware default string encodings.
482 import locale
483 loc = locale.getdefaultlocale()
484 if loc[1]:
485 encoding = loc[1]
486 if 0:
487 # Enable to switch off string to Unicode coercion and implicit
488 # Unicode to string conversion.
489 encoding = "undefined"
490 if encoding != "ascii":
491 # On Non-Unicode builds this will raise an AttributeError...
492 sys.setdefaultencoding(encoding) # Needs Python Unicode build !
Guido van Rossum83213cc2001-06-12 16:48:52 +0000493
494
Brett Cannon0096e262004-06-05 01:12:51 +0000495def execsitecustomize():
496 """Run custom site specific code, if available."""
497 try:
498 import sitecustomize
499 except ImportError:
500 pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000501 except Exception as err:
Guido van Rossumc6fe9832006-08-19 00:10:28 +0000502 if os.environ.get("PYTHONVERBOSE"):
Victor Stinner52f6dd72010-03-12 14:45:56 +0000503 sys.excepthook(*sys.exc_info())
504 else:
505 sys.stderr.write(
506 "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
507 "%s: %s\n" %
508 (err.__class__.__name__, err))
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000509
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000510
Christian Heimes8dc226f2008-05-06 23:45:46 +0000511def execusercustomize():
512 """Run custom user specific code, if available."""
513 try:
514 import usercustomize
515 except ImportError:
516 pass
Victor Stinner52f6dd72010-03-12 14:45:56 +0000517 except Exception as err:
518 if os.environ.get("PYTHONVERBOSE"):
519 sys.excepthook(*sys.exc_info())
520 else:
521 sys.stderr.write(
522 "Error in usercustomize; set PYTHONVERBOSE for traceback:\n"
523 "%s: %s\n" %
524 (err.__class__.__name__, err))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000525
526
Brett Cannon0096e262004-06-05 01:12:51 +0000527def main():
Christian Heimes8dc226f2008-05-06 23:45:46 +0000528 global ENABLE_USER_SITE
529
Barry Warsaw28a691b2010-04-17 00:19:56 +0000530 abs_paths()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000531 known_paths = removeduppaths()
Brett Cannon0096e262004-06-05 01:12:51 +0000532 if (os.name == "posix" and sys.path and
533 os.path.basename(sys.path[-1]) == "Modules"):
534 addbuilddir()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000535 if ENABLE_USER_SITE is None:
536 ENABLE_USER_SITE = check_enableusersite()
537 known_paths = addusersitepackages(known_paths)
538 known_paths = addsitepackages(known_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000539 if sys.platform == 'os2emx':
540 setBEGINLIBPATH()
541 setquit()
542 setcopyright()
543 sethelper()
544 aliasmbcs()
545 setencoding()
546 execsitecustomize()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000547 if ENABLE_USER_SITE:
548 execusercustomize()
Brett Cannon0096e262004-06-05 01:12:51 +0000549 # Remove sys.setdefaultencoding() so that users cannot change the
550 # encoding after initialization. The test for presence is needed when
551 # this module is run as a script, because this code is executed twice.
552 if hasattr(sys, "setdefaultencoding"):
553 del sys.setdefaultencoding
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000554
Brett Cannon0096e262004-06-05 01:12:51 +0000555main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000556
Christian Heimes8dc226f2008-05-06 23:45:46 +0000557def _script():
558 help = """\
559 %s [--user-base] [--user-site]
560
561 Without arguments print some useful information
562 With arguments print the value of USER_BASE and/or USER_SITE separated
563 by '%s'.
564
565 Exit codes with --user-base or --user-site:
566 0 - user site directory is enabled
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000567 1 - user site directory is disabled by user
Christian Heimes8dc226f2008-05-06 23:45:46 +0000568 2 - uses site directory is disabled by super user
569 or for security reasons
570 >2 - unknown error
571 """
572 args = sys.argv[1:]
573 if not args:
574 print("sys.path = [")
575 for dir in sys.path:
576 print(" %r," % (dir,))
577 print("]")
578 print("USER_BASE: %r (%s)" % (USER_BASE,
579 "exists" if os.path.isdir(USER_BASE) else "doesn't exist"))
580 print("USER_SITE: %r (%s)" % (USER_SITE,
581 "exists" if os.path.isdir(USER_SITE) else "doesn't exist"))
582 print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE)
583 sys.exit(0)
584
585 buffer = []
586 if '--user-base' in args:
587 buffer.append(USER_BASE)
588 if '--user-site' in args:
589 buffer.append(USER_SITE)
590
591 if buffer:
592 print(os.pathsep.join(buffer))
593 if ENABLE_USER_SITE:
594 sys.exit(0)
595 elif ENABLE_USER_SITE is False:
596 sys.exit(1)
597 elif ENABLE_USER_SITE is None:
598 sys.exit(2)
599 else:
600 sys.exit(3)
601 else:
602 import textwrap
603 print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
604 sys.exit(10)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000605
606if __name__ == '__main__':
Christian Heimes8dc226f2008-05-06 23:45:46 +0000607 _script()