blob: 55e662c0b0fd15ac3220285441f8c658f15e30d5 [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
Brett Cannon0096e262004-06-05 01:12:51 +000077def abs__file__():
78 """Set all module' __file__ attribute 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:
85 continue
Fred Drake38cb9f12000-09-28 16:52:36 +000086
Christian Heimes8dc226f2008-05-06 23:45:46 +000087
Brett Cannon0096e262004-06-05 01:12:51 +000088def removeduppaths():
89 """ Remove duplicate entries from sys.path along with making them
90 absolute"""
91 # This ensures that the initial path provided by the interpreter contains
92 # only absolute pathnames, even if we're running from the build directory.
93 L = []
94 known_paths = set()
95 for dir in sys.path:
96 # Filter out duplicate paths (on case-insensitive file systems also
97 # if they only differ in case); turn relative paths into absolute
98 # paths.
99 dir, dircase = makepath(dir)
100 if not dircase in known_paths:
101 L.append(dir)
102 known_paths.add(dircase)
103 sys.path[:] = L
104 return known_paths
Fred Drake38cb9f12000-09-28 16:52:36 +0000105
Fred Drakee80c0d32002-07-25 20:13:03 +0000106# XXX This should not be part of site.py, since it is needed even when
107# using the -S option for Python. See http://www.python.org/sf/586680
Brett Cannon0096e262004-06-05 01:12:51 +0000108def addbuilddir():
109 """Append ./build/lib.<platform> in case we're running in the build dir
110 (especially for Guido :-)"""
Tarek Ziadéedacea32010-01-29 11:41:03 +0000111 from sysconfig import get_platform
Jeremy Hylton6d58bf62003-07-18 17:45:33 +0000112 s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
Christian Heimes1af737c2008-01-23 08:24:23 +0000113 if hasattr(sys, 'gettotalrefcount'):
114 s += '-pydebug'
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000115 s = os.path.join(os.path.dirname(sys.path.pop()), s)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000116 sys.path.append(s)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000117
Christian Heimes8dc226f2008-05-06 23:45:46 +0000118
Fred Drake7f5296e2001-07-20 20:06:17 +0000119def _init_pathinfo():
Brett Cannon0096e262004-06-05 01:12:51 +0000120 """Return a set containing all existing directory entries from sys.path"""
121 d = set()
Fred Drake7f5296e2001-07-20 20:06:17 +0000122 for dir in sys.path:
Brett Cannon0096e262004-06-05 01:12:51 +0000123 try:
124 if os.path.isdir(dir):
125 dir, dircase = makepath(dir)
126 d.add(dircase)
127 except TypeError:
Fred Drake7f5296e2001-07-20 20:06:17 +0000128 continue
Brett Cannon0096e262004-06-05 01:12:51 +0000129 return d
Fred Drake7f5296e2001-07-20 20:06:17 +0000130
Christian Heimes8dc226f2008-05-06 23:45:46 +0000131
Brett Cannon0096e262004-06-05 01:12:51 +0000132def addpackage(sitedir, name, known_paths):
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000133 """Process a .pth file within the site-packages directory:
134 For each line in the file, either combine it with sitedir to a path
135 and add that to known_paths, or execute it if it starts with 'import '.
136 """
Brett Cannon0096e262004-06-05 01:12:51 +0000137 if known_paths is None:
Fred Drake7f5296e2001-07-20 20:06:17 +0000138 _init_pathinfo()
139 reset = 1
140 else:
141 reset = 0
Brett Cannon0096e262004-06-05 01:12:51 +0000142 fullname = os.path.join(sitedir, name)
143 try:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000144 f = open(fullname, "rU")
Brett Cannon0096e262004-06-05 01:12:51 +0000145 except IOError:
146 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000147 with f:
Brett Cannon0096e262004-06-05 01:12:51 +0000148 for line in f:
149 if line.startswith("#"):
150 continue
Christian Heimes8dc226f2008-05-06 23:45:46 +0000151 if line.startswith(("import ", "import\t")):
Georg Brandl7cae87c2006-09-06 06:51:57 +0000152 exec(line)
Brett Cannon0096e262004-06-05 01:12:51 +0000153 continue
154 line = line.rstrip()
155 dir, dircase = makepath(sitedir, line)
156 if not dircase in known_paths and os.path.exists(dir):
157 sys.path.append(dir)
158 known_paths.add(dircase)
Brett Cannon0096e262004-06-05 01:12:51 +0000159 if reset:
160 known_paths = None
161 return known_paths
162
Christian Heimes8dc226f2008-05-06 23:45:46 +0000163
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000164def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000165 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
166 'sitedir'"""
167 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000168 known_paths = _init_pathinfo()
Brett Cannon0096e262004-06-05 01:12:51 +0000169 reset = 1
170 else:
171 reset = 0
Fred Drake1fb5ce02001-07-02 16:55:42 +0000172 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000173 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000174 sys.path.append(sitedir) # Add path component
Guido van Rossumf30bec71997-08-29 22:30:45 +0000175 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000176 names = os.listdir(sitedir)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000177 except os.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000178 return
Christian Heimes8dc226f2008-05-06 23:45:46 +0000179 names = [name for name in names if name.endswith(".pth")]
180 for name in sorted(names):
181 addpackage(sitedir, name, known_paths)
Fred Drake7f5296e2001-07-20 20:06:17 +0000182 if reset:
Brett Cannon0096e262004-06-05 01:12:51 +0000183 known_paths = None
184 return known_paths
Guido van Rossumf30bec71997-08-29 22:30:45 +0000185
Christian Heimes8dc226f2008-05-06 23:45:46 +0000186
187def check_enableusersite():
188 """Check if user site directory is safe for inclusion
189
Alexandre Vassalottia79e33e2008-05-15 22:51:26 +0000190 The function tests for the command line flag (including environment var),
Christian Heimes8dc226f2008-05-06 23:45:46 +0000191 process uid/gid equal to effective uid/gid.
192
193 None: Disabled for security reasons
194 False: Disabled by user (command line option)
195 True: Safe and enabled
196 """
197 if sys.flags.no_user_site:
198 return False
199
200 if hasattr(os, "getuid") and hasattr(os, "geteuid"):
201 # check process uid == effective uid
202 if os.geteuid() != os.getuid():
203 return None
204 if hasattr(os, "getgid") and hasattr(os, "getegid"):
205 # check process gid == effective gid
206 if os.getegid() != os.getgid():
207 return None
208
209 return True
210
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000211def getuserbase():
212 """Returns the `user base` directory path.
213
214 The `user base` directory can be used to store data. If the global
215 variable ``USER_BASE`` is not initialized yet, this function will also set
216 it.
217 """
218 global USER_BASE
219 if USER_BASE is not None:
220 return USER_BASE
Tarek Ziadéedacea32010-01-29 11:41:03 +0000221 from sysconfig import get_config_var
222 USER_BASE = get_config_var('userbase')
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000223 return USER_BASE
224
225def getusersitepackages():
226 """Returns the user-specific site-packages directory path.
227
228 If the global variable ``USER_SITE`` is not initialized yet, this
229 function will also set it.
230 """
231 global USER_SITE
232 user_base = getuserbase() # this will also set USER_BASE
233
234 if USER_SITE is not None:
235 return USER_SITE
236
Tarek Ziadéedacea32010-01-29 11:41:03 +0000237 from sysconfig import get_path
238 import os
239 USER_SITE = get_path('purelib', '%s_user' % os.name)
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000240 return USER_SITE
Christian Heimes8dc226f2008-05-06 23:45:46 +0000241
242def addusersitepackages(known_paths):
243 """Add a per user site-package to sys.path
244
245 Each user has its own python directory with site-packages in the
246 home directory.
Christian Heimes8dc226f2008-05-06 23:45:46 +0000247 """
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000248 # get the per user site-package path
249 # this call will also make sure USER_BASE and USER_SITE are set
250 user_site = getusersitepackages()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000251
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000252 if ENABLE_USER_SITE and os.path.isdir(user_site):
253 addsitedir(user_site, known_paths)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000254 return known_paths
255
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000256def getsitepackages():
257 """Returns a list containing all global site-packages directories
258 (and possibly site-python).
Christian Heimes8dc226f2008-05-06 23:45:46 +0000259
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000260 For each directory present in the global ``PREFIXES``, this function
261 will find its `site-packages` subdirectory depending on the system
262 environment, and will return a list of full paths.
263 """
264 sitepackages = []
Christian Heimes8dc226f2008-05-06 23:45:46 +0000265 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'):
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000273 sitepackages.append(os.path.join(prefix, "Lib", "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000274 elif os.sep == '/':
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000275 sitepackages.append(os.path.join(prefix, "lib",
Christian Heimes8dc226f2008-05-06 23:45:46 +0000276 "python" + sys.version[:3],
277 "site-packages"))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000278 sitepackages.append(os.path.join(prefix, "lib", "site-python"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000279 else:
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000280 sitepackages.append(prefix)
281 sitepackages.append(os.path.join(prefix, "lib", "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000282 if sys.platform == "darwin":
283 # for framework builds *only* we add the standard Apple
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000284 # locations.
Christian Heimes8dc226f2008-05-06 23:45:46 +0000285 if 'Python.framework' in prefix:
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000286 sitepackages.append(
Christian Heimes8dc226f2008-05-06 23:45:46 +0000287 os.path.expanduser(
288 os.path.join("~", "Library", "Python",
289 sys.version[:3], "site-packages")))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000290 sitepackages.append(
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000291 os.path.join("/Library", "Python",
292 sys.version[:3], "site-packages"))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000293 return sitepackages
Christian Heimes8dc226f2008-05-06 23:45:46 +0000294
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000295def addsitepackages(known_paths):
296 """Add site-packages (and possibly site-python) to sys.path"""
297 for sitedir in getsitepackages():
Christian Heimes8dc226f2008-05-06 23:45:46 +0000298 if os.path.isdir(sitedir):
299 addsitedir(sitedir, known_paths)
300
301 return known_paths
Fred Drake7f5296e2001-07-20 20:06:17 +0000302
Brett Cannon0096e262004-06-05 01:12:51 +0000303def setBEGINLIBPATH():
304 """The OS/2 EMX port has optional extension modules that do double duty
305 as DLLs (and must use the .DLL file extension) for other extensions.
306 The library search path needs to be amended so these will be found
307 during module import. Use BEGINLIBPATH so that these are at the start
308 of the library search path.
Tim Peters4e0e1b62004-07-07 20:54:48 +0000309
Brett Cannon0096e262004-06-05 01:12:51 +0000310 """
Andrew MacIntyre2e8a6e02003-12-02 12:27:25 +0000311 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
312 libpath = os.environ['BEGINLIBPATH'].split(';')
313 if libpath[-1]:
314 libpath.append(dllpath)
315 else:
316 libpath[-1] = dllpath
317 os.environ['BEGINLIBPATH'] = ';'.join(libpath)
318
319
Brett Cannon0096e262004-06-05 01:12:51 +0000320def setquit():
Brian Curtinfb1d3c12010-04-12 23:33:42 +0000321 """Define new builtins 'quit' and 'exit'.
322
323 These are objects which make the interpreter exit when called.
324 The repr of each object contains a hint at how it works.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000325
Brett Cannon0096e262004-06-05 01:12:51 +0000326 """
327 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000328 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000329 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000330 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000331 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000332 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000333
Georg Brandl24cb0532006-03-09 23:22:06 +0000334 class Quitter(object):
335 def __init__(self, name):
336 self.name = name
337 def __repr__(self):
338 return 'Use %s() or %s to exit' % (self.name, eof)
339 def __call__(self, code=None):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000340 # Shells like IDLE catch the SystemExit, but listen when their
341 # stdin wrapper is closed.
342 try:
Christian Heimes862543a2007-12-31 03:07:24 +0000343 fd = -1
344 if hasattr(sys.stdin, "fileno"):
345 fd = sys.stdin.fileno()
346 if fd != 0:
347 # Don't close stdin if it wraps fd 0
348 sys.stdin.close()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000349 except:
350 pass
Georg Brandl24cb0532006-03-09 23:22:06 +0000351 raise SystemExit(code)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000352 builtins.quit = Quitter('quit')
353 builtins.exit = Quitter('exit')
Brett Cannon0096e262004-06-05 01:12:51 +0000354
355
356class _Printer(object):
357 """interactive prompt objects for printing the license text, a list of
358 contributors and the copyright notice."""
359
Guido van Rossumd1252392000-09-05 04:39:55 +0000360 MAXLINES = 23
361
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000362 def __init__(self, name, data, files=(), dirs=()):
363 self.__name = name
364 self.__data = data
365 self.__files = files
366 self.__dirs = dirs
367 self.__lines = None
368
369 def __setup(self):
370 if self.__lines:
371 return
372 data = None
373 for dir in self.__dirs:
Brett Cannon0096e262004-06-05 01:12:51 +0000374 for filename in self.__files:
375 filename = os.path.join(dir, filename)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000376 try:
Alex Martelli01c77c62006-08-24 02:58:11 +0000377 fp = open(filename, "rU")
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000378 data = fp.read()
379 fp.close()
380 break
381 except IOError:
382 pass
383 if data:
384 break
385 if not data:
386 data = self.__data
387 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000388 self.__linecnt = len(self.__lines)
389
390 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000391 self.__setup()
392 if len(self.__lines) <= self.MAXLINES:
393 return "\n".join(self.__lines)
394 else:
395 return "Type %s() to see the full %s text" % ((self.__name,)*2)
396
397 def __call__(self):
398 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000399 prompt = 'Hit Return for more, or q (and Return) to quit: '
400 lineno = 0
401 while 1:
402 try:
403 for i in range(lineno, lineno + self.MAXLINES):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000404 print(self.__lines[i])
Guido van Rossumd1252392000-09-05 04:39:55 +0000405 except IndexError:
406 break
407 else:
408 lineno += self.MAXLINES
409 key = None
410 while key is None:
Guido van Rossum704b34d2007-12-20 18:42:56 +0000411 key = input(prompt)
Guido van Rossumd1252392000-09-05 04:39:55 +0000412 if key not in ('', 'q'):
413 key = None
414 if key == 'q':
415 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000416
Brett Cannon0096e262004-06-05 01:12:51 +0000417def setcopyright():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000418 """Set 'copyright' and 'credits' in builtins"""
419 builtins.copyright = _Printer("copyright", sys.copyright)
Brett Cannon0096e262004-06-05 01:12:51 +0000420 if sys.platform[:4] == 'java':
Georg Brandl1a3284e2007-12-02 09:40:06 +0000421 builtins.credits = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000422 "credits",
423 "Jython is maintained by the Jython developers (www.jython.org).")
424 else:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000425 builtins.credits = _Printer("credits", """\
Brett Cannon0096e262004-06-05 01:12:51 +0000426 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
427 for supporting Python development. See www.python.org for more information.""")
428 here = os.path.dirname(os.__file__)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000429 builtins.license = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000430 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
431 ["LICENSE.txt", "LICENSE"],
432 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000433
434
Brett Cannon0096e262004-06-05 01:12:51 +0000435class _Helper(object):
Brian Curtinfb1d3c12010-04-12 23:33:42 +0000436 """Define the builtin 'help'.
Brett Cannon0096e262004-06-05 01:12:51 +0000437 This is a wrapper around pydoc.help (with a twist).
Guido van Rossum83213cc2001-06-12 16:48:52 +0000438
Brett Cannon0096e262004-06-05 01:12:51 +0000439 """
440
Guido van Rossum83213cc2001-06-12 16:48:52 +0000441 def __repr__(self):
442 return "Type help() for interactive help, " \
443 "or help(object) for help about object."
444 def __call__(self, *args, **kwds):
445 import pydoc
446 return pydoc.help(*args, **kwds)
447
Brett Cannon0096e262004-06-05 01:12:51 +0000448def sethelper():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000449 builtins.help = _Helper()
Brett Cannon0096e262004-06-05 01:12:51 +0000450
451def aliasmbcs():
452 """On Windows, some default encodings are not provided by Python,
453 while they are always available as "mbcs" in each locale. Make
454 them usable by aliasing to "mbcs" in such a case."""
455 if sys.platform == 'win32':
456 import locale, codecs
457 enc = locale.getdefaultlocale()[1]
458 if enc.startswith('cp'): # "cp***" ?
459 try:
460 codecs.lookup(enc)
461 except LookupError:
462 import encodings
463 encodings._cache[enc] = encodings._unknown
464 encodings.aliases.aliases[enc] = 'mbcs'
465
466def setencoding():
467 """Set the string encoding used by the Unicode implementation. The
468 default is 'ascii', but if you're willing to experiment, you can
469 change this."""
470 encoding = "ascii" # Default value set by _PyUnicode_Init()
471 if 0:
472 # Enable to support locale aware default string encodings.
473 import locale
474 loc = locale.getdefaultlocale()
475 if loc[1]:
476 encoding = loc[1]
477 if 0:
478 # Enable to switch off string to Unicode coercion and implicit
479 # Unicode to string conversion.
480 encoding = "undefined"
481 if encoding != "ascii":
482 # On Non-Unicode builds this will raise an AttributeError...
483 sys.setdefaultencoding(encoding) # Needs Python Unicode build !
Guido van Rossum83213cc2001-06-12 16:48:52 +0000484
485
Brett Cannon0096e262004-06-05 01:12:51 +0000486def execsitecustomize():
487 """Run custom site specific code, if available."""
488 try:
489 import sitecustomize
490 except ImportError:
491 pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000492 except Exception as err:
Guido van Rossumc6fe9832006-08-19 00:10:28 +0000493 if os.environ.get("PYTHONVERBOSE"):
Victor Stinner52f6dd72010-03-12 14:45:56 +0000494 sys.excepthook(*sys.exc_info())
495 else:
496 sys.stderr.write(
497 "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
498 "%s: %s\n" %
499 (err.__class__.__name__, err))
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000500
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000501
Christian Heimes8dc226f2008-05-06 23:45:46 +0000502def execusercustomize():
503 """Run custom user specific code, if available."""
504 try:
505 import usercustomize
506 except ImportError:
507 pass
Victor Stinner52f6dd72010-03-12 14:45:56 +0000508 except Exception as err:
509 if os.environ.get("PYTHONVERBOSE"):
510 sys.excepthook(*sys.exc_info())
511 else:
512 sys.stderr.write(
513 "Error in usercustomize; set PYTHONVERBOSE for traceback:\n"
514 "%s: %s\n" %
515 (err.__class__.__name__, err))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000516
517
Brett Cannon0096e262004-06-05 01:12:51 +0000518def main():
Christian Heimes8dc226f2008-05-06 23:45:46 +0000519 global ENABLE_USER_SITE
520
Brett Cannon0096e262004-06-05 01:12:51 +0000521 abs__file__()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000522 known_paths = removeduppaths()
Brett Cannon0096e262004-06-05 01:12:51 +0000523 if (os.name == "posix" and sys.path and
524 os.path.basename(sys.path[-1]) == "Modules"):
525 addbuilddir()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000526 if ENABLE_USER_SITE is None:
527 ENABLE_USER_SITE = check_enableusersite()
528 known_paths = addusersitepackages(known_paths)
529 known_paths = addsitepackages(known_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000530 if sys.platform == 'os2emx':
531 setBEGINLIBPATH()
532 setquit()
533 setcopyright()
534 sethelper()
535 aliasmbcs()
536 setencoding()
537 execsitecustomize()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000538 if ENABLE_USER_SITE:
539 execusercustomize()
Brett Cannon0096e262004-06-05 01:12:51 +0000540 # Remove sys.setdefaultencoding() so that users cannot change the
541 # encoding after initialization. The test for presence is needed when
542 # this module is run as a script, because this code is executed twice.
543 if hasattr(sys, "setdefaultencoding"):
544 del sys.setdefaultencoding
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000545
Brett Cannon0096e262004-06-05 01:12:51 +0000546main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000547
Christian Heimes8dc226f2008-05-06 23:45:46 +0000548def _script():
549 help = """\
550 %s [--user-base] [--user-site]
551
552 Without arguments print some useful information
553 With arguments print the value of USER_BASE and/or USER_SITE separated
554 by '%s'.
555
556 Exit codes with --user-base or --user-site:
557 0 - user site directory is enabled
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000558 1 - user site directory is disabled by user
Christian Heimes8dc226f2008-05-06 23:45:46 +0000559 2 - uses site directory is disabled by super user
560 or for security reasons
561 >2 - unknown error
562 """
563 args = sys.argv[1:]
564 if not args:
565 print("sys.path = [")
566 for dir in sys.path:
567 print(" %r," % (dir,))
568 print("]")
569 print("USER_BASE: %r (%s)" % (USER_BASE,
570 "exists" if os.path.isdir(USER_BASE) else "doesn't exist"))
571 print("USER_SITE: %r (%s)" % (USER_SITE,
572 "exists" if os.path.isdir(USER_SITE) else "doesn't exist"))
573 print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE)
574 sys.exit(0)
575
576 buffer = []
577 if '--user-base' in args:
578 buffer.append(USER_BASE)
579 if '--user-site' in args:
580 buffer.append(USER_SITE)
581
582 if buffer:
583 print(os.pathsep.join(buffer))
584 if ENABLE_USER_SITE:
585 sys.exit(0)
586 elif ENABLE_USER_SITE is False:
587 sys.exit(1)
588 elif ENABLE_USER_SITE is None:
589 sys.exit(2)
590 else:
591 sys.exit(3)
592 else:
593 import textwrap
594 print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
595 sys.exit(10)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000596
597if __name__ == '__main__':
Christian Heimes8dc226f2008-05-06 23:45:46 +0000598 _script()