blob: 3d455e79e238c0c45e1a43e1d88ac5405117d93e [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 :-)"""
Jeremy Hylton6d58bf62003-07-18 17:45:33 +0000111 from distutils.util import get_platform
112 s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
Christian Heimes1af737c2008-01-23 08:24:23 +0000113 if hasattr(sys, 'gettotalrefcount'):
114 s += '-pydebug'
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000115 s = os.path.join(os.path.dirname(sys.path[-1]), s)
116 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
221
222 env_base = os.environ.get("PYTHONUSERBASE", None)
223
224 def joinuser(*args):
225 return os.path.expanduser(os.path.join(*args))
226
227 # what about 'os2emx', 'riscos' ?
228 if os.name == "nt":
229 base = os.environ.get("APPDATA") or "~"
230 USER_BASE = env_base if env_base else joinuser(base, "Python")
231 else:
232 USER_BASE = env_base if env_base else joinuser("~", ".local")
233
234 return USER_BASE
235
236def getusersitepackages():
237 """Returns the user-specific site-packages directory path.
238
239 If the global variable ``USER_SITE`` is not initialized yet, this
240 function will also set it.
241 """
242 global USER_SITE
243 user_base = getuserbase() # this will also set USER_BASE
244
245 if USER_SITE is not None:
246 return USER_SITE
247
248 if os.name == "nt":
249 USER_SITE = os.path.join(user_base, "Python" + sys.version[0] +
250 sys.version[2], "site-packages")
251 else:
252 USER_SITE = os.path.join(user_base, "lib", "python" + sys.version[:3],
253 "site-packages")
254
255 return USER_SITE
Christian Heimes8dc226f2008-05-06 23:45:46 +0000256
257def addusersitepackages(known_paths):
258 """Add a per user site-package to sys.path
259
260 Each user has its own python directory with site-packages in the
261 home directory.
Christian Heimes8dc226f2008-05-06 23:45:46 +0000262 """
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000263 # get the per user site-package path
264 # this call will also make sure USER_BASE and USER_SITE are set
265 user_site = getusersitepackages()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000266
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000267 if ENABLE_USER_SITE and os.path.isdir(user_site):
268 addsitedir(user_site, known_paths)
Christian Heimes8dc226f2008-05-06 23:45:46 +0000269 return known_paths
270
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000271def getsitepackages():
272 """Returns a list containing all global site-packages directories
273 (and possibly site-python).
Christian Heimes8dc226f2008-05-06 23:45:46 +0000274
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000275 For each directory present in the global ``PREFIXES``, this function
276 will find its `site-packages` subdirectory depending on the system
277 environment, and will return a list of full paths.
278 """
279 sitepackages = []
Christian Heimes8dc226f2008-05-06 23:45:46 +0000280 seen = []
281
282 for prefix in PREFIXES:
283 if not prefix or prefix in seen:
284 continue
285 seen.append(prefix)
286
287 if sys.platform in ('os2emx', 'riscos'):
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000288 sitepackages.append(os.path.join(prefix, "Lib", "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000289 elif os.sep == '/':
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000290 sitepackages.append(os.path.join(prefix, "lib",
Christian Heimes8dc226f2008-05-06 23:45:46 +0000291 "python" + sys.version[:3],
292 "site-packages"))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000293 sitepackages.append(os.path.join(prefix, "lib", "site-python"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000294 else:
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000295 sitepackages.append(prefix)
296 sitepackages.append(os.path.join(prefix, "lib", "site-packages"))
Christian Heimes8dc226f2008-05-06 23:45:46 +0000297 if sys.platform == "darwin":
298 # for framework builds *only* we add the standard Apple
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000299 # locations.
Christian Heimes8dc226f2008-05-06 23:45:46 +0000300 if 'Python.framework' in prefix:
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000301 sitepackages.append(
Christian Heimes8dc226f2008-05-06 23:45:46 +0000302 os.path.expanduser(
303 os.path.join("~", "Library", "Python",
304 sys.version[:3], "site-packages")))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000305 sitepackages.append(
Ronald Oussorenfa1fcd12009-03-30 23:16:10 +0000306 os.path.join("/Library", "Python",
307 sys.version[:3], "site-packages"))
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000308 return sitepackages
Christian Heimes8dc226f2008-05-06 23:45:46 +0000309
Tarek Ziadé4a608c02009-08-20 21:28:05 +0000310def addsitepackages(known_paths):
311 """Add site-packages (and possibly site-python) to sys.path"""
312 for sitedir in getsitepackages():
Christian Heimes8dc226f2008-05-06 23:45:46 +0000313 if os.path.isdir(sitedir):
314 addsitedir(sitedir, known_paths)
315
316 return known_paths
Fred Drake7f5296e2001-07-20 20:06:17 +0000317
Brett Cannon0096e262004-06-05 01:12:51 +0000318def setBEGINLIBPATH():
319 """The OS/2 EMX port has optional extension modules that do double duty
320 as DLLs (and must use the .DLL file extension) for other extensions.
321 The library search path needs to be amended so these will be found
322 during module import. Use BEGINLIBPATH so that these are at the start
323 of the library search path.
Tim Peters4e0e1b62004-07-07 20:54:48 +0000324
Brett Cannon0096e262004-06-05 01:12:51 +0000325 """
Andrew MacIntyre2e8a6e02003-12-02 12:27:25 +0000326 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
327 libpath = os.environ['BEGINLIBPATH'].split(';')
328 if libpath[-1]:
329 libpath.append(dllpath)
330 else:
331 libpath[-1] = dllpath
332 os.environ['BEGINLIBPATH'] = ';'.join(libpath)
333
334
Brett Cannon0096e262004-06-05 01:12:51 +0000335def setquit():
336 """Define new built-ins 'quit' and 'exit'.
337 These are simply strings that display a hint on how to exit.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000338
Brett Cannon0096e262004-06-05 01:12:51 +0000339 """
340 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000341 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000342 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000343 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000344 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000345 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000346
Georg Brandl24cb0532006-03-09 23:22:06 +0000347 class Quitter(object):
348 def __init__(self, name):
349 self.name = name
350 def __repr__(self):
351 return 'Use %s() or %s to exit' % (self.name, eof)
352 def __call__(self, code=None):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000353 # Shells like IDLE catch the SystemExit, but listen when their
354 # stdin wrapper is closed.
355 try:
Christian Heimes862543a2007-12-31 03:07:24 +0000356 fd = -1
357 if hasattr(sys.stdin, "fileno"):
358 fd = sys.stdin.fileno()
359 if fd != 0:
360 # Don't close stdin if it wraps fd 0
361 sys.stdin.close()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000362 except:
363 pass
Georg Brandl24cb0532006-03-09 23:22:06 +0000364 raise SystemExit(code)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000365 builtins.quit = Quitter('quit')
366 builtins.exit = Quitter('exit')
Brett Cannon0096e262004-06-05 01:12:51 +0000367
368
369class _Printer(object):
370 """interactive prompt objects for printing the license text, a list of
371 contributors and the copyright notice."""
372
Guido van Rossumd1252392000-09-05 04:39:55 +0000373 MAXLINES = 23
374
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000375 def __init__(self, name, data, files=(), dirs=()):
376 self.__name = name
377 self.__data = data
378 self.__files = files
379 self.__dirs = dirs
380 self.__lines = None
381
382 def __setup(self):
383 if self.__lines:
384 return
385 data = None
386 for dir in self.__dirs:
Brett Cannon0096e262004-06-05 01:12:51 +0000387 for filename in self.__files:
388 filename = os.path.join(dir, filename)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000389 try:
Alex Martelli01c77c62006-08-24 02:58:11 +0000390 fp = open(filename, "rU")
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000391 data = fp.read()
392 fp.close()
393 break
394 except IOError:
395 pass
396 if data:
397 break
398 if not data:
399 data = self.__data
400 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000401 self.__linecnt = len(self.__lines)
402
403 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000404 self.__setup()
405 if len(self.__lines) <= self.MAXLINES:
406 return "\n".join(self.__lines)
407 else:
408 return "Type %s() to see the full %s text" % ((self.__name,)*2)
409
410 def __call__(self):
411 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000412 prompt = 'Hit Return for more, or q (and Return) to quit: '
413 lineno = 0
414 while 1:
415 try:
416 for i in range(lineno, lineno + self.MAXLINES):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000417 print(self.__lines[i])
Guido van Rossumd1252392000-09-05 04:39:55 +0000418 except IndexError:
419 break
420 else:
421 lineno += self.MAXLINES
422 key = None
423 while key is None:
Guido van Rossum704b34d2007-12-20 18:42:56 +0000424 key = input(prompt)
Guido van Rossumd1252392000-09-05 04:39:55 +0000425 if key not in ('', 'q'):
426 key = None
427 if key == 'q':
428 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000429
Brett Cannon0096e262004-06-05 01:12:51 +0000430def setcopyright():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000431 """Set 'copyright' and 'credits' in builtins"""
432 builtins.copyright = _Printer("copyright", sys.copyright)
Brett Cannon0096e262004-06-05 01:12:51 +0000433 if sys.platform[:4] == 'java':
Georg Brandl1a3284e2007-12-02 09:40:06 +0000434 builtins.credits = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000435 "credits",
436 "Jython is maintained by the Jython developers (www.jython.org).")
437 else:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000438 builtins.credits = _Printer("credits", """\
Brett Cannon0096e262004-06-05 01:12:51 +0000439 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
440 for supporting Python development. See www.python.org for more information.""")
441 here = os.path.dirname(os.__file__)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000442 builtins.license = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000443 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
444 ["LICENSE.txt", "LICENSE"],
445 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000446
447
Brett Cannon0096e262004-06-05 01:12:51 +0000448class _Helper(object):
449 """Define the built-in 'help'.
450 This is a wrapper around pydoc.help (with a twist).
Guido van Rossum83213cc2001-06-12 16:48:52 +0000451
Brett Cannon0096e262004-06-05 01:12:51 +0000452 """
453
Guido van Rossum83213cc2001-06-12 16:48:52 +0000454 def __repr__(self):
455 return "Type help() for interactive help, " \
456 "or help(object) for help about object."
457 def __call__(self, *args, **kwds):
458 import pydoc
459 return pydoc.help(*args, **kwds)
460
Brett Cannon0096e262004-06-05 01:12:51 +0000461def sethelper():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000462 builtins.help = _Helper()
Brett Cannon0096e262004-06-05 01:12:51 +0000463
464def aliasmbcs():
465 """On Windows, some default encodings are not provided by Python,
466 while they are always available as "mbcs" in each locale. Make
467 them usable by aliasing to "mbcs" in such a case."""
468 if sys.platform == 'win32':
469 import locale, codecs
470 enc = locale.getdefaultlocale()[1]
471 if enc.startswith('cp'): # "cp***" ?
472 try:
473 codecs.lookup(enc)
474 except LookupError:
475 import encodings
476 encodings._cache[enc] = encodings._unknown
477 encodings.aliases.aliases[enc] = 'mbcs'
478
479def setencoding():
480 """Set the string encoding used by the Unicode implementation. The
481 default is 'ascii', but if you're willing to experiment, you can
482 change this."""
483 encoding = "ascii" # Default value set by _PyUnicode_Init()
484 if 0:
485 # Enable to support locale aware default string encodings.
486 import locale
487 loc = locale.getdefaultlocale()
488 if loc[1]:
489 encoding = loc[1]
490 if 0:
491 # Enable to switch off string to Unicode coercion and implicit
492 # Unicode to string conversion.
493 encoding = "undefined"
494 if encoding != "ascii":
495 # On Non-Unicode builds this will raise an AttributeError...
496 sys.setdefaultencoding(encoding) # Needs Python Unicode build !
Guido van Rossum83213cc2001-06-12 16:48:52 +0000497
498
Brett Cannon0096e262004-06-05 01:12:51 +0000499def execsitecustomize():
500 """Run custom site specific code, if available."""
501 try:
502 import sitecustomize
503 except ImportError:
504 pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000505 except Exception as err:
Guido van Rossumc6fe9832006-08-19 00:10:28 +0000506 if os.environ.get("PYTHONVERBOSE"):
507 raise
508 sys.stderr.write(
509 "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
510 "%s: %s\n" %
511 (err.__class__.__name__, err))
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000512
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000513
Christian Heimes8dc226f2008-05-06 23:45:46 +0000514def execusercustomize():
515 """Run custom user specific code, if available."""
516 try:
517 import usercustomize
518 except ImportError:
519 pass
520
521
Brett Cannon0096e262004-06-05 01:12:51 +0000522def main():
Christian Heimes8dc226f2008-05-06 23:45:46 +0000523 global ENABLE_USER_SITE
524
Brett Cannon0096e262004-06-05 01:12:51 +0000525 abs__file__()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000526 known_paths = removeduppaths()
Brett Cannon0096e262004-06-05 01:12:51 +0000527 if (os.name == "posix" and sys.path and
528 os.path.basename(sys.path[-1]) == "Modules"):
529 addbuilddir()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000530 if ENABLE_USER_SITE is None:
531 ENABLE_USER_SITE = check_enableusersite()
532 known_paths = addusersitepackages(known_paths)
533 known_paths = addsitepackages(known_paths)
Brett Cannon0096e262004-06-05 01:12:51 +0000534 if sys.platform == 'os2emx':
535 setBEGINLIBPATH()
536 setquit()
537 setcopyright()
538 sethelper()
539 aliasmbcs()
540 setencoding()
541 execsitecustomize()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000542 if ENABLE_USER_SITE:
543 execusercustomize()
Brett Cannon0096e262004-06-05 01:12:51 +0000544 # Remove sys.setdefaultencoding() so that users cannot change the
545 # encoding after initialization. The test for presence is needed when
546 # this module is run as a script, because this code is executed twice.
547 if hasattr(sys, "setdefaultencoding"):
548 del sys.setdefaultencoding
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000549
Brett Cannon0096e262004-06-05 01:12:51 +0000550main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000551
Christian Heimes8dc226f2008-05-06 23:45:46 +0000552def _script():
553 help = """\
554 %s [--user-base] [--user-site]
555
556 Without arguments print some useful information
557 With arguments print the value of USER_BASE and/or USER_SITE separated
558 by '%s'.
559
560 Exit codes with --user-base or --user-site:
561 0 - user site directory is enabled
Alexandre Vassalotti6461e102008-05-15 22:09:29 +0000562 1 - user site directory is disabled by user
Christian Heimes8dc226f2008-05-06 23:45:46 +0000563 2 - uses site directory is disabled by super user
564 or for security reasons
565 >2 - unknown error
566 """
567 args = sys.argv[1:]
568 if not args:
569 print("sys.path = [")
570 for dir in sys.path:
571 print(" %r," % (dir,))
572 print("]")
573 print("USER_BASE: %r (%s)" % (USER_BASE,
574 "exists" if os.path.isdir(USER_BASE) else "doesn't exist"))
575 print("USER_SITE: %r (%s)" % (USER_SITE,
576 "exists" if os.path.isdir(USER_SITE) else "doesn't exist"))
577 print("ENABLE_USER_SITE: %r" % ENABLE_USER_SITE)
578 sys.exit(0)
579
580 buffer = []
581 if '--user-base' in args:
582 buffer.append(USER_BASE)
583 if '--user-site' in args:
584 buffer.append(USER_SITE)
585
586 if buffer:
587 print(os.pathsep.join(buffer))
588 if ENABLE_USER_SITE:
589 sys.exit(0)
590 elif ENABLE_USER_SITE is False:
591 sys.exit(1)
592 elif ENABLE_USER_SITE is None:
593 sys.exit(2)
594 else:
595 sys.exit(3)
596 else:
597 import textwrap
598 print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
599 sys.exit(10)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000600
601if __name__ == '__main__':
Christian Heimes8dc226f2008-05-06 23:45:46 +0000602 _script()