blob: 56af90e66b110f5d3866c8af37dba6805a68bf5a [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
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000059
Fred Drake38cb9f12000-09-28 16:52:36 +000060def makepath(*paths):
Fred Drake1fb5ce02001-07-02 16:55:42 +000061 dir = os.path.abspath(os.path.join(*paths))
62 return dir, os.path.normcase(dir)
Fred Drake38cb9f12000-09-28 16:52:36 +000063
Brett Cannon0096e262004-06-05 01:12:51 +000064def abs__file__():
65 """Set all module' __file__ attribute to an absolute path"""
Guido van Rossum7ac9d402007-05-18 00:24:43 +000066 for m in set(sys.modules.values()):
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000067 if hasattr(m, '__loader__'):
68 continue # don't mess with a PEP 302-supplied __file__
Brett Cannon0096e262004-06-05 01:12:51 +000069 try:
70 m.__file__ = os.path.abspath(m.__file__)
71 except AttributeError:
72 continue
Fred Drake38cb9f12000-09-28 16:52:36 +000073
Brett Cannon0096e262004-06-05 01:12:51 +000074def removeduppaths():
75 """ Remove duplicate entries from sys.path along with making them
76 absolute"""
77 # This ensures that the initial path provided by the interpreter contains
78 # only absolute pathnames, even if we're running from the build directory.
79 L = []
80 known_paths = set()
81 for dir in sys.path:
82 # Filter out duplicate paths (on case-insensitive file systems also
83 # if they only differ in case); turn relative paths into absolute
84 # paths.
85 dir, dircase = makepath(dir)
86 if not dircase in known_paths:
87 L.append(dir)
88 known_paths.add(dircase)
89 sys.path[:] = L
90 return known_paths
Fred Drake38cb9f12000-09-28 16:52:36 +000091
Fred Drakee80c0d32002-07-25 20:13:03 +000092# XXX This should not be part of site.py, since it is needed even when
93# using the -S option for Python. See http://www.python.org/sf/586680
Brett Cannon0096e262004-06-05 01:12:51 +000094def addbuilddir():
95 """Append ./build/lib.<platform> in case we're running in the build dir
96 (especially for Guido :-)"""
Jeremy Hylton6d58bf62003-07-18 17:45:33 +000097 from distutils.util import get_platform
98 s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +000099 s = os.path.join(os.path.dirname(sys.path[-1]), s)
100 sys.path.append(s)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000101
Fred Drake7f5296e2001-07-20 20:06:17 +0000102def _init_pathinfo():
Brett Cannon0096e262004-06-05 01:12:51 +0000103 """Return a set containing all existing directory entries from sys.path"""
104 d = set()
Fred Drake7f5296e2001-07-20 20:06:17 +0000105 for dir in sys.path:
Brett Cannon0096e262004-06-05 01:12:51 +0000106 try:
107 if os.path.isdir(dir):
108 dir, dircase = makepath(dir)
109 d.add(dircase)
110 except TypeError:
Fred Drake7f5296e2001-07-20 20:06:17 +0000111 continue
Brett Cannon0096e262004-06-05 01:12:51 +0000112 return d
Fred Drake7f5296e2001-07-20 20:06:17 +0000113
Brett Cannon0096e262004-06-05 01:12:51 +0000114def addpackage(sitedir, name, known_paths):
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000115 """Process a .pth file within the site-packages directory:
116 For each line in the file, either combine it with sitedir to a path
117 and add that to known_paths, or execute it if it starts with 'import '.
118 """
Brett Cannon0096e262004-06-05 01:12:51 +0000119 if known_paths is None:
Fred Drake7f5296e2001-07-20 20:06:17 +0000120 _init_pathinfo()
121 reset = 1
122 else:
123 reset = 0
Brett Cannon0096e262004-06-05 01:12:51 +0000124 fullname = os.path.join(sitedir, name)
125 try:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000126 f = open(fullname, "rU")
Brett Cannon0096e262004-06-05 01:12:51 +0000127 except IOError:
128 return
129 try:
130 for line in f:
131 if line.startswith("#"):
132 continue
Guido van Rossumd8faa362007-04-27 19:54:29 +0000133 if line.startswith("import ") or line.startswith("import\t"):
Georg Brandl7cae87c2006-09-06 06:51:57 +0000134 exec(line)
Brett Cannon0096e262004-06-05 01:12:51 +0000135 continue
136 line = line.rstrip()
137 dir, dircase = makepath(sitedir, line)
138 if not dircase in known_paths and os.path.exists(dir):
139 sys.path.append(dir)
140 known_paths.add(dircase)
141 finally:
142 f.close()
143 if reset:
144 known_paths = None
145 return known_paths
146
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000147def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000148 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
149 'sitedir'"""
150 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000151 known_paths = _init_pathinfo()
Brett Cannon0096e262004-06-05 01:12:51 +0000152 reset = 1
153 else:
154 reset = 0
Fred Drake1fb5ce02001-07-02 16:55:42 +0000155 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000156 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000157 sys.path.append(sitedir) # Add path component
Guido van Rossumf30bec71997-08-29 22:30:45 +0000158 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000159 names = os.listdir(sitedir)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000160 except os.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000161 return
Guido van Rossumf30bec71997-08-29 22:30:45 +0000162 names.sort()
163 for name in names:
Skip Montanaro7a98be22007-08-16 14:35:24 +0000164 if name.endswith(".pth"):
Brett Cannon0096e262004-06-05 01:12:51 +0000165 addpackage(sitedir, name, known_paths)
Fred Drake7f5296e2001-07-20 20:06:17 +0000166 if reset:
Brett Cannon0096e262004-06-05 01:12:51 +0000167 known_paths = None
168 return known_paths
Guido van Rossumf30bec71997-08-29 22:30:45 +0000169
Brett Cannon0096e262004-06-05 01:12:51 +0000170def addsitepackages(known_paths):
171 """Add site-packages (and possibly site-python) to sys.path"""
172 prefixes = [sys.prefix]
173 if sys.exec_prefix != sys.prefix:
174 prefixes.append(sys.exec_prefix)
175 for prefix in prefixes:
176 if prefix:
Skip Montanaro289bc052007-08-17 02:30:27 +0000177 if sys.platform == 'os2emx':
Brett Cannon0096e262004-06-05 01:12:51 +0000178 sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
179 elif os.sep == '/':
180 sitedirs = [os.path.join(prefix,
181 "lib",
182 "python" + sys.version[:3],
183 "site-packages"),
184 os.path.join(prefix, "lib", "site-python")]
185 else:
186 sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
187 if sys.platform == 'darwin':
188 # for framework builds *only* we add the standard Apple
189 # locations. Currently only per-user, but /Library and
190 # /Network/Library could be added too
191 if 'Python.framework' in prefix:
192 home = os.environ.get('HOME')
193 if home:
194 sitedirs.append(
195 os.path.join(home,
196 'Library',
197 'Python',
198 sys.version[:3],
199 'site-packages'))
200 for sitedir in sitedirs:
201 if os.path.isdir(sitedir):
202 addsitedir(sitedir, known_paths)
203 return None
Fred Drake7f5296e2001-07-20 20:06:17 +0000204
Fred Drake1fb5ce02001-07-02 16:55:42 +0000205
Brett Cannon0096e262004-06-05 01:12:51 +0000206def setBEGINLIBPATH():
207 """The OS/2 EMX port has optional extension modules that do double duty
208 as DLLs (and must use the .DLL file extension) for other extensions.
209 The library search path needs to be amended so these will be found
210 during module import. Use BEGINLIBPATH so that these are at the start
211 of the library search path.
Tim Peters4e0e1b62004-07-07 20:54:48 +0000212
Brett Cannon0096e262004-06-05 01:12:51 +0000213 """
Andrew MacIntyre2e8a6e02003-12-02 12:27:25 +0000214 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
215 libpath = os.environ['BEGINLIBPATH'].split(';')
216 if libpath[-1]:
217 libpath.append(dllpath)
218 else:
219 libpath[-1] = dllpath
220 os.environ['BEGINLIBPATH'] = ';'.join(libpath)
221
222
Brett Cannon0096e262004-06-05 01:12:51 +0000223def setquit():
224 """Define new built-ins 'quit' and 'exit'.
225 These are simply strings that display a hint on how to exit.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000226
Brett Cannon0096e262004-06-05 01:12:51 +0000227 """
228 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000229 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000230 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000231 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000232 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000233 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000234
Georg Brandl24cb0532006-03-09 23:22:06 +0000235 class Quitter(object):
236 def __init__(self, name):
237 self.name = name
238 def __repr__(self):
239 return 'Use %s() or %s to exit' % (self.name, eof)
240 def __call__(self, code=None):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000241 # Shells like IDLE catch the SystemExit, but listen when their
242 # stdin wrapper is closed.
243 try:
Christian Heimes862543a2007-12-31 03:07:24 +0000244 fd = -1
245 if hasattr(sys.stdin, "fileno"):
246 fd = sys.stdin.fileno()
247 if fd != 0:
248 # Don't close stdin if it wraps fd 0
249 sys.stdin.close()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000250 except:
251 pass
Georg Brandl24cb0532006-03-09 23:22:06 +0000252 raise SystemExit(code)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000253 builtins.quit = Quitter('quit')
254 builtins.exit = Quitter('exit')
Brett Cannon0096e262004-06-05 01:12:51 +0000255
256
257class _Printer(object):
258 """interactive prompt objects for printing the license text, a list of
259 contributors and the copyright notice."""
260
Guido van Rossumd1252392000-09-05 04:39:55 +0000261 MAXLINES = 23
262
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000263 def __init__(self, name, data, files=(), dirs=()):
264 self.__name = name
265 self.__data = data
266 self.__files = files
267 self.__dirs = dirs
268 self.__lines = None
269
270 def __setup(self):
271 if self.__lines:
272 return
273 data = None
274 for dir in self.__dirs:
Brett Cannon0096e262004-06-05 01:12:51 +0000275 for filename in self.__files:
276 filename = os.path.join(dir, filename)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000277 try:
Alex Martelli01c77c62006-08-24 02:58:11 +0000278 fp = open(filename, "rU")
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000279 data = fp.read()
280 fp.close()
281 break
282 except IOError:
283 pass
284 if data:
285 break
286 if not data:
287 data = self.__data
288 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000289 self.__linecnt = len(self.__lines)
290
291 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000292 self.__setup()
293 if len(self.__lines) <= self.MAXLINES:
294 return "\n".join(self.__lines)
295 else:
296 return "Type %s() to see the full %s text" % ((self.__name,)*2)
297
298 def __call__(self):
299 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000300 prompt = 'Hit Return for more, or q (and Return) to quit: '
301 lineno = 0
302 while 1:
303 try:
304 for i in range(lineno, lineno + self.MAXLINES):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000305 print(self.__lines[i])
Guido van Rossumd1252392000-09-05 04:39:55 +0000306 except IndexError:
307 break
308 else:
309 lineno += self.MAXLINES
310 key = None
311 while key is None:
Guido van Rossum704b34d2007-12-20 18:42:56 +0000312 key = input(prompt)
Guido van Rossumd1252392000-09-05 04:39:55 +0000313 if key not in ('', 'q'):
314 key = None
315 if key == 'q':
316 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000317
Brett Cannon0096e262004-06-05 01:12:51 +0000318def setcopyright():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000319 """Set 'copyright' and 'credits' in builtins"""
320 builtins.copyright = _Printer("copyright", sys.copyright)
Brett Cannon0096e262004-06-05 01:12:51 +0000321 if sys.platform[:4] == 'java':
Georg Brandl1a3284e2007-12-02 09:40:06 +0000322 builtins.credits = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000323 "credits",
324 "Jython is maintained by the Jython developers (www.jython.org).")
325 else:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000326 builtins.credits = _Printer("credits", """\
Brett Cannon0096e262004-06-05 01:12:51 +0000327 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
328 for supporting Python development. See www.python.org for more information.""")
329 here = os.path.dirname(os.__file__)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000330 builtins.license = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000331 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
332 ["LICENSE.txt", "LICENSE"],
333 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000334
335
Brett Cannon0096e262004-06-05 01:12:51 +0000336class _Helper(object):
337 """Define the built-in 'help'.
338 This is a wrapper around pydoc.help (with a twist).
Guido van Rossum83213cc2001-06-12 16:48:52 +0000339
Brett Cannon0096e262004-06-05 01:12:51 +0000340 """
341
Guido van Rossum83213cc2001-06-12 16:48:52 +0000342 def __repr__(self):
343 return "Type help() for interactive help, " \
344 "or help(object) for help about object."
345 def __call__(self, *args, **kwds):
346 import pydoc
347 return pydoc.help(*args, **kwds)
348
Brett Cannon0096e262004-06-05 01:12:51 +0000349def sethelper():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000350 builtins.help = _Helper()
Brett Cannon0096e262004-06-05 01:12:51 +0000351
352def aliasmbcs():
353 """On Windows, some default encodings are not provided by Python,
354 while they are always available as "mbcs" in each locale. Make
355 them usable by aliasing to "mbcs" in such a case."""
356 if sys.platform == 'win32':
357 import locale, codecs
358 enc = locale.getdefaultlocale()[1]
359 if enc.startswith('cp'): # "cp***" ?
360 try:
361 codecs.lookup(enc)
362 except LookupError:
363 import encodings
364 encodings._cache[enc] = encodings._unknown
365 encodings.aliases.aliases[enc] = 'mbcs'
366
367def setencoding():
368 """Set the string encoding used by the Unicode implementation. The
369 default is 'ascii', but if you're willing to experiment, you can
370 change this."""
371 encoding = "ascii" # Default value set by _PyUnicode_Init()
372 if 0:
373 # Enable to support locale aware default string encodings.
374 import locale
375 loc = locale.getdefaultlocale()
376 if loc[1]:
377 encoding = loc[1]
378 if 0:
379 # Enable to switch off string to Unicode coercion and implicit
380 # Unicode to string conversion.
381 encoding = "undefined"
382 if encoding != "ascii":
383 # On Non-Unicode builds this will raise an AttributeError...
384 sys.setdefaultencoding(encoding) # Needs Python Unicode build !
Guido van Rossum83213cc2001-06-12 16:48:52 +0000385
386
Brett Cannon0096e262004-06-05 01:12:51 +0000387def execsitecustomize():
388 """Run custom site specific code, if available."""
389 try:
390 import sitecustomize
391 except ImportError:
392 pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000393 except Exception as err:
Guido van Rossumc6fe9832006-08-19 00:10:28 +0000394 if os.environ.get("PYTHONVERBOSE"):
395 raise
396 sys.stderr.write(
397 "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
398 "%s: %s\n" %
399 (err.__class__.__name__, err))
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000400
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000401
Brett Cannon0096e262004-06-05 01:12:51 +0000402def main():
403 abs__file__()
404 paths_in_sys = removeduppaths()
405 if (os.name == "posix" and sys.path and
406 os.path.basename(sys.path[-1]) == "Modules"):
407 addbuilddir()
408 paths_in_sys = addsitepackages(paths_in_sys)
409 if sys.platform == 'os2emx':
410 setBEGINLIBPATH()
411 setquit()
412 setcopyright()
413 sethelper()
414 aliasmbcs()
415 setencoding()
416 execsitecustomize()
417 # Remove sys.setdefaultencoding() so that users cannot change the
418 # encoding after initialization. The test for presence is needed when
419 # this module is run as a script, because this code is executed twice.
420 if hasattr(sys, "setdefaultencoding"):
421 del sys.setdefaultencoding
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000422
Brett Cannon0096e262004-06-05 01:12:51 +0000423main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000424
425def _test():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000426 print("sys.path = [")
Guido van Rossumf30bec71997-08-29 22:30:45 +0000427 for dir in sys.path:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000428 print(" %r," % (dir,))
429 print("]")
Guido van Rossumf30bec71997-08-29 22:30:45 +0000430
431if __name__ == '__main__':
432 _test()