blob: 3ba42121f6b03fea82870a65bd46556d91caa6a0 [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
Guido van Rossumf30bec71997-08-29 22:30:45 +00007In earlier versions of Python (up to 1.5a3), scripts or modules that
8needed to use site-specific modules would place ``import site''
9somewhere near the top of their code. Because of the automatic
10import, this is no longer necessary (but code that does it still
11works).
Guido van Rossume57c96e1996-08-17 19:56:26 +000012
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +000013This will append site-specific paths to the module search path. On
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014Unix (including Mac OSX), it starts with sys.prefix and
15sys.exec_prefix (if different) and appends
16lib/python<version>/site-packages as well as lib/site-python.
17On other platforms (such as Windows), it tries each of the
18prefixes directly, as well as with lib/site-packages appended. The
Guido van Rossum62b297b1997-09-08 02:14:09 +000019resulting directories, if they exist, are appended to sys.path, and
20also inspected for path configuration files.
Guido van Rossume57c96e1996-08-17 19:56:26 +000021
Guido van Rossumf30bec71997-08-29 22:30:45 +000022A path configuration file is a file whose name has the form
23<package>.pth; its contents are additional directories (one per line)
24to be added to sys.path. Non-existing directories (or
25non-directories) are never added to sys.path; no directory is added to
26sys.path more than once. Blank lines and lines beginning with
Guido van Rossumfacf24b2001-12-17 16:07:06 +000027'#' are skipped. Lines starting with 'import' are executed.
Guido van Rossume57c96e1996-08-17 19:56:26 +000028
Guido van Rossumf30bec71997-08-29 22:30:45 +000029For example, suppose sys.prefix and sys.exec_prefix are set to
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000030/usr/local and there is a directory /usr/local/lib/python2.5/site-packages
Guido van Rossum62b297b1997-09-08 02:14:09 +000031with three subdirectories, foo, bar and spam, and two path
32configuration files, foo.pth and bar.pth. Assume foo.pth contains the
33following:
Guido van Rossumf30bec71997-08-29 22:30:45 +000034
35 # foo package configuration
36 foo
37 bar
38 bletch
39
40and bar.pth contains:
41
42 # bar package configuration
43 bar
44
45Then the following directories are added to sys.path, in this order:
46
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000047 /usr/local/lib/python2.5/site-packages/bar
48 /usr/local/lib/python2.5/site-packages/foo
Guido van Rossumf30bec71997-08-29 22:30:45 +000049
50Note that bletch is omitted because it doesn't exist; bar precedes foo
51because bar.pth comes alphabetically before foo.pth; and spam is
52omitted because it is not mentioned in either path configuration file.
Guido van Rossume57c96e1996-08-17 19:56:26 +000053
54After these path manipulations, an attempt is made to import a module
Guido van Rossumf30bec71997-08-29 22:30:45 +000055named sitecustomize, which can perform arbitrary additional
56site-specific customizations. If this import fails with an
57ImportError exception, it is silently ignored.
Guido van Rossume57c96e1996-08-17 19:56:26 +000058
Guido van Rossume57c96e1996-08-17 19:56:26 +000059"""
60
Brett Cannon0096e262004-06-05 01:12:51 +000061import sys
62import os
Georg Brandl1a3284e2007-12-02 09:40:06 +000063import builtins
Guido van Rossume57c96e1996-08-17 19:56:26 +000064
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000065
Fred Drake38cb9f12000-09-28 16:52:36 +000066def makepath(*paths):
Fred Drake1fb5ce02001-07-02 16:55:42 +000067 dir = os.path.abspath(os.path.join(*paths))
68 return dir, os.path.normcase(dir)
Fred Drake38cb9f12000-09-28 16:52:36 +000069
Brett Cannon0096e262004-06-05 01:12:51 +000070def abs__file__():
71 """Set all module' __file__ attribute to an absolute path"""
Guido van Rossum7ac9d402007-05-18 00:24:43 +000072 for m in set(sys.modules.values()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000073 if hasattr(m, '__loader__'):
74 continue # don't mess with a PEP 302-supplied __file__
Brett Cannon0096e262004-06-05 01:12:51 +000075 try:
76 m.__file__ = os.path.abspath(m.__file__)
77 except AttributeError:
78 continue
Fred Drake38cb9f12000-09-28 16:52:36 +000079
Brett Cannon0096e262004-06-05 01:12:51 +000080def removeduppaths():
81 """ Remove duplicate entries from sys.path along with making them
82 absolute"""
83 # This ensures that the initial path provided by the interpreter contains
84 # only absolute pathnames, even if we're running from the build directory.
85 L = []
86 known_paths = set()
87 for dir in sys.path:
88 # Filter out duplicate paths (on case-insensitive file systems also
89 # if they only differ in case); turn relative paths into absolute
90 # paths.
91 dir, dircase = makepath(dir)
92 if not dircase in known_paths:
93 L.append(dir)
94 known_paths.add(dircase)
95 sys.path[:] = L
96 return known_paths
Fred Drake38cb9f12000-09-28 16:52:36 +000097
Fred Drakee80c0d32002-07-25 20:13:03 +000098# XXX This should not be part of site.py, since it is needed even when
99# using the -S option for Python. See http://www.python.org/sf/586680
Brett Cannon0096e262004-06-05 01:12:51 +0000100def addbuilddir():
101 """Append ./build/lib.<platform> in case we're running in the build dir
102 (especially for Guido :-)"""
Jeremy Hylton6d58bf62003-07-18 17:45:33 +0000103 from distutils.util import get_platform
104 s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000105 s = os.path.join(os.path.dirname(sys.path[-1]), s)
106 sys.path.append(s)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000107
Fred Drake7f5296e2001-07-20 20:06:17 +0000108def _init_pathinfo():
Brett Cannon0096e262004-06-05 01:12:51 +0000109 """Return a set containing all existing directory entries from sys.path"""
110 d = set()
Fred Drake7f5296e2001-07-20 20:06:17 +0000111 for dir in sys.path:
Brett Cannon0096e262004-06-05 01:12:51 +0000112 try:
113 if os.path.isdir(dir):
114 dir, dircase = makepath(dir)
115 d.add(dircase)
116 except TypeError:
Fred Drake7f5296e2001-07-20 20:06:17 +0000117 continue
Brett Cannon0096e262004-06-05 01:12:51 +0000118 return d
Fred Drake7f5296e2001-07-20 20:06:17 +0000119
Brett Cannon0096e262004-06-05 01:12:51 +0000120def addpackage(sitedir, name, known_paths):
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000121 """Process a .pth file within the site-packages directory:
122 For each line in the file, either combine it with sitedir to a path
123 and add that to known_paths, or execute it if it starts with 'import '.
124 """
Brett Cannon0096e262004-06-05 01:12:51 +0000125 if known_paths is None:
Fred Drake7f5296e2001-07-20 20:06:17 +0000126 _init_pathinfo()
127 reset = 1
128 else:
129 reset = 0
Brett Cannon0096e262004-06-05 01:12:51 +0000130 fullname = os.path.join(sitedir, name)
131 try:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000132 f = open(fullname, "rU")
Brett Cannon0096e262004-06-05 01:12:51 +0000133 except IOError:
134 return
135 try:
136 for line in f:
137 if line.startswith("#"):
138 continue
Guido van Rossumd8faa362007-04-27 19:54:29 +0000139 if line.startswith("import ") or line.startswith("import\t"):
Georg Brandl7cae87c2006-09-06 06:51:57 +0000140 exec(line)
Brett Cannon0096e262004-06-05 01:12:51 +0000141 continue
142 line = line.rstrip()
143 dir, dircase = makepath(sitedir, line)
144 if not dircase in known_paths and os.path.exists(dir):
145 sys.path.append(dir)
146 known_paths.add(dircase)
147 finally:
148 f.close()
149 if reset:
150 known_paths = None
151 return known_paths
152
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000153def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000154 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
155 'sitedir'"""
156 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000157 known_paths = _init_pathinfo()
Brett Cannon0096e262004-06-05 01:12:51 +0000158 reset = 1
159 else:
160 reset = 0
Fred Drake1fb5ce02001-07-02 16:55:42 +0000161 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000162 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000163 sys.path.append(sitedir) # Add path component
Guido van Rossumf30bec71997-08-29 22:30:45 +0000164 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000165 names = os.listdir(sitedir)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000166 except os.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000167 return
Guido van Rossumf30bec71997-08-29 22:30:45 +0000168 names.sort()
169 for name in names:
Skip Montanaro7a98be22007-08-16 14:35:24 +0000170 if name.endswith(".pth"):
Brett Cannon0096e262004-06-05 01:12:51 +0000171 addpackage(sitedir, name, known_paths)
Fred Drake7f5296e2001-07-20 20:06:17 +0000172 if reset:
Brett Cannon0096e262004-06-05 01:12:51 +0000173 known_paths = None
174 return known_paths
Guido van Rossumf30bec71997-08-29 22:30:45 +0000175
Brett Cannon0096e262004-06-05 01:12:51 +0000176def addsitepackages(known_paths):
177 """Add site-packages (and possibly site-python) to sys.path"""
178 prefixes = [sys.prefix]
179 if sys.exec_prefix != sys.prefix:
180 prefixes.append(sys.exec_prefix)
181 for prefix in prefixes:
182 if prefix:
Skip Montanaro289bc052007-08-17 02:30:27 +0000183 if sys.platform == 'os2emx':
Brett Cannon0096e262004-06-05 01:12:51 +0000184 sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
185 elif os.sep == '/':
186 sitedirs = [os.path.join(prefix,
187 "lib",
188 "python" + sys.version[:3],
189 "site-packages"),
190 os.path.join(prefix, "lib", "site-python")]
191 else:
192 sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
193 if sys.platform == 'darwin':
194 # for framework builds *only* we add the standard Apple
195 # locations. Currently only per-user, but /Library and
196 # /Network/Library could be added too
197 if 'Python.framework' in prefix:
198 home = os.environ.get('HOME')
199 if home:
200 sitedirs.append(
201 os.path.join(home,
202 'Library',
203 'Python',
204 sys.version[:3],
205 'site-packages'))
206 for sitedir in sitedirs:
207 if os.path.isdir(sitedir):
208 addsitedir(sitedir, known_paths)
209 return None
Fred Drake7f5296e2001-07-20 20:06:17 +0000210
Fred Drake1fb5ce02001-07-02 16:55:42 +0000211
Brett Cannon0096e262004-06-05 01:12:51 +0000212def setBEGINLIBPATH():
213 """The OS/2 EMX port has optional extension modules that do double duty
214 as DLLs (and must use the .DLL file extension) for other extensions.
215 The library search path needs to be amended so these will be found
216 during module import. Use BEGINLIBPATH so that these are at the start
217 of the library search path.
Tim Peters4e0e1b62004-07-07 20:54:48 +0000218
Brett Cannon0096e262004-06-05 01:12:51 +0000219 """
Andrew MacIntyre2e8a6e02003-12-02 12:27:25 +0000220 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
221 libpath = os.environ['BEGINLIBPATH'].split(';')
222 if libpath[-1]:
223 libpath.append(dllpath)
224 else:
225 libpath[-1] = dllpath
226 os.environ['BEGINLIBPATH'] = ';'.join(libpath)
227
228
Brett Cannon0096e262004-06-05 01:12:51 +0000229def setquit():
230 """Define new built-ins 'quit' and 'exit'.
231 These are simply strings that display a hint on how to exit.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000232
Brett Cannon0096e262004-06-05 01:12:51 +0000233 """
234 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000235 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000236 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000237 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000238 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000239 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000240
Georg Brandl24cb0532006-03-09 23:22:06 +0000241 class Quitter(object):
242 def __init__(self, name):
243 self.name = name
244 def __repr__(self):
245 return 'Use %s() or %s to exit' % (self.name, eof)
246 def __call__(self, code=None):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000247 # Shells like IDLE catch the SystemExit, but listen when their
248 # stdin wrapper is closed.
249 try:
Christian Heimes862543a2007-12-31 03:07:24 +0000250 fd = -1
251 if hasattr(sys.stdin, "fileno"):
252 fd = sys.stdin.fileno()
253 if fd != 0:
254 # Don't close stdin if it wraps fd 0
255 sys.stdin.close()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000256 except:
257 pass
Georg Brandl24cb0532006-03-09 23:22:06 +0000258 raise SystemExit(code)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000259 builtins.quit = Quitter('quit')
260 builtins.exit = Quitter('exit')
Brett Cannon0096e262004-06-05 01:12:51 +0000261
262
263class _Printer(object):
264 """interactive prompt objects for printing the license text, a list of
265 contributors and the copyright notice."""
266
Guido van Rossumd1252392000-09-05 04:39:55 +0000267 MAXLINES = 23
268
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000269 def __init__(self, name, data, files=(), dirs=()):
270 self.__name = name
271 self.__data = data
272 self.__files = files
273 self.__dirs = dirs
274 self.__lines = None
275
276 def __setup(self):
277 if self.__lines:
278 return
279 data = None
280 for dir in self.__dirs:
Brett Cannon0096e262004-06-05 01:12:51 +0000281 for filename in self.__files:
282 filename = os.path.join(dir, filename)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000283 try:
Alex Martelli01c77c62006-08-24 02:58:11 +0000284 fp = open(filename, "rU")
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000285 data = fp.read()
286 fp.close()
287 break
288 except IOError:
289 pass
290 if data:
291 break
292 if not data:
293 data = self.__data
294 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000295 self.__linecnt = len(self.__lines)
296
297 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000298 self.__setup()
299 if len(self.__lines) <= self.MAXLINES:
300 return "\n".join(self.__lines)
301 else:
302 return "Type %s() to see the full %s text" % ((self.__name,)*2)
303
304 def __call__(self):
305 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000306 prompt = 'Hit Return for more, or q (and Return) to quit: '
307 lineno = 0
308 while 1:
309 try:
310 for i in range(lineno, lineno + self.MAXLINES):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000311 print(self.__lines[i])
Guido van Rossumd1252392000-09-05 04:39:55 +0000312 except IndexError:
313 break
314 else:
315 lineno += self.MAXLINES
316 key = None
317 while key is None:
Guido van Rossum704b34d2007-12-20 18:42:56 +0000318 key = input(prompt)
Guido van Rossumd1252392000-09-05 04:39:55 +0000319 if key not in ('', 'q'):
320 key = None
321 if key == 'q':
322 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000323
Brett Cannon0096e262004-06-05 01:12:51 +0000324def setcopyright():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000325 """Set 'copyright' and 'credits' in builtins"""
326 builtins.copyright = _Printer("copyright", sys.copyright)
Brett Cannon0096e262004-06-05 01:12:51 +0000327 if sys.platform[:4] == 'java':
Georg Brandl1a3284e2007-12-02 09:40:06 +0000328 builtins.credits = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000329 "credits",
330 "Jython is maintained by the Jython developers (www.jython.org).")
331 else:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000332 builtins.credits = _Printer("credits", """\
Brett Cannon0096e262004-06-05 01:12:51 +0000333 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
334 for supporting Python development. See www.python.org for more information.""")
335 here = os.path.dirname(os.__file__)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000336 builtins.license = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000337 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
338 ["LICENSE.txt", "LICENSE"],
339 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000340
341
Brett Cannon0096e262004-06-05 01:12:51 +0000342class _Helper(object):
343 """Define the built-in 'help'.
344 This is a wrapper around pydoc.help (with a twist).
Guido van Rossum83213cc2001-06-12 16:48:52 +0000345
Brett Cannon0096e262004-06-05 01:12:51 +0000346 """
347
Guido van Rossum83213cc2001-06-12 16:48:52 +0000348 def __repr__(self):
349 return "Type help() for interactive help, " \
350 "or help(object) for help about object."
351 def __call__(self, *args, **kwds):
352 import pydoc
353 return pydoc.help(*args, **kwds)
354
Brett Cannon0096e262004-06-05 01:12:51 +0000355def sethelper():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000356 builtins.help = _Helper()
Brett Cannon0096e262004-06-05 01:12:51 +0000357
358def aliasmbcs():
359 """On Windows, some default encodings are not provided by Python,
360 while they are always available as "mbcs" in each locale. Make
361 them usable by aliasing to "mbcs" in such a case."""
362 if sys.platform == 'win32':
363 import locale, codecs
364 enc = locale.getdefaultlocale()[1]
365 if enc.startswith('cp'): # "cp***" ?
366 try:
367 codecs.lookup(enc)
368 except LookupError:
369 import encodings
370 encodings._cache[enc] = encodings._unknown
371 encodings.aliases.aliases[enc] = 'mbcs'
372
373def setencoding():
374 """Set the string encoding used by the Unicode implementation. The
375 default is 'ascii', but if you're willing to experiment, you can
376 change this."""
377 encoding = "ascii" # Default value set by _PyUnicode_Init()
378 if 0:
379 # Enable to support locale aware default string encodings.
380 import locale
381 loc = locale.getdefaultlocale()
382 if loc[1]:
383 encoding = loc[1]
384 if 0:
385 # Enable to switch off string to Unicode coercion and implicit
386 # Unicode to string conversion.
387 encoding = "undefined"
388 if encoding != "ascii":
389 # On Non-Unicode builds this will raise an AttributeError...
390 sys.setdefaultencoding(encoding) # Needs Python Unicode build !
Guido van Rossum83213cc2001-06-12 16:48:52 +0000391
392
Brett Cannon0096e262004-06-05 01:12:51 +0000393def execsitecustomize():
394 """Run custom site specific code, if available."""
395 try:
396 import sitecustomize
397 except ImportError:
398 pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000399 except Exception as err:
Guido van Rossumc6fe9832006-08-19 00:10:28 +0000400 if os.environ.get("PYTHONVERBOSE"):
401 raise
402 sys.stderr.write(
403 "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
404 "%s: %s\n" %
405 (err.__class__.__name__, err))
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000406
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000407
Brett Cannon0096e262004-06-05 01:12:51 +0000408def main():
409 abs__file__()
410 paths_in_sys = removeduppaths()
411 if (os.name == "posix" and sys.path and
412 os.path.basename(sys.path[-1]) == "Modules"):
413 addbuilddir()
414 paths_in_sys = addsitepackages(paths_in_sys)
415 if sys.platform == 'os2emx':
416 setBEGINLIBPATH()
417 setquit()
418 setcopyright()
419 sethelper()
420 aliasmbcs()
421 setencoding()
422 execsitecustomize()
423 # Remove sys.setdefaultencoding() so that users cannot change the
424 # encoding after initialization. The test for presence is needed when
425 # this module is run as a script, because this code is executed twice.
426 if hasattr(sys, "setdefaultencoding"):
427 del sys.setdefaultencoding
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000428
Brett Cannon0096e262004-06-05 01:12:51 +0000429main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000430
431def _test():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000432 print("sys.path = [")
Guido van Rossumf30bec71997-08-29 22:30:45 +0000433 for dir in sys.path:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000434 print(" %r," % (dir,))
435 print("]")
Guido van Rossumf30bec71997-08-29 22:30:45 +0000436
437if __name__ == '__main__':
438 _test()