blob: fc68317bb87d0a3f7829711a7e72a3ba176c59a9 [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)
Christian Heimes1af737c2008-01-23 08:24:23 +000099 if hasattr(sys, 'gettotalrefcount'):
100 s += '-pydebug'
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000101 s = os.path.join(os.path.dirname(sys.path[-1]), s)
102 sys.path.append(s)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000103
Fred Drake7f5296e2001-07-20 20:06:17 +0000104def _init_pathinfo():
Brett Cannon0096e262004-06-05 01:12:51 +0000105 """Return a set containing all existing directory entries from sys.path"""
106 d = set()
Fred Drake7f5296e2001-07-20 20:06:17 +0000107 for dir in sys.path:
Brett Cannon0096e262004-06-05 01:12:51 +0000108 try:
109 if os.path.isdir(dir):
110 dir, dircase = makepath(dir)
111 d.add(dircase)
112 except TypeError:
Fred Drake7f5296e2001-07-20 20:06:17 +0000113 continue
Brett Cannon0096e262004-06-05 01:12:51 +0000114 return d
Fred Drake7f5296e2001-07-20 20:06:17 +0000115
Brett Cannon0096e262004-06-05 01:12:51 +0000116def addpackage(sitedir, name, known_paths):
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000117 """Process a .pth file within the site-packages directory:
118 For each line in the file, either combine it with sitedir to a path
119 and add that to known_paths, or execute it if it starts with 'import '.
120 """
Brett Cannon0096e262004-06-05 01:12:51 +0000121 if known_paths is None:
Fred Drake7f5296e2001-07-20 20:06:17 +0000122 _init_pathinfo()
123 reset = 1
124 else:
125 reset = 0
Brett Cannon0096e262004-06-05 01:12:51 +0000126 fullname = os.path.join(sitedir, name)
127 try:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000128 f = open(fullname, "rU")
Brett Cannon0096e262004-06-05 01:12:51 +0000129 except IOError:
130 return
131 try:
132 for line in f:
133 if line.startswith("#"):
134 continue
Guido van Rossumd8faa362007-04-27 19:54:29 +0000135 if line.startswith("import ") or line.startswith("import\t"):
Georg Brandl7cae87c2006-09-06 06:51:57 +0000136 exec(line)
Brett Cannon0096e262004-06-05 01:12:51 +0000137 continue
138 line = line.rstrip()
139 dir, dircase = makepath(sitedir, line)
140 if not dircase in known_paths and os.path.exists(dir):
141 sys.path.append(dir)
142 known_paths.add(dircase)
143 finally:
144 f.close()
145 if reset:
146 known_paths = None
147 return known_paths
148
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000149def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000150 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
151 'sitedir'"""
152 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000153 known_paths = _init_pathinfo()
Brett Cannon0096e262004-06-05 01:12:51 +0000154 reset = 1
155 else:
156 reset = 0
Fred Drake1fb5ce02001-07-02 16:55:42 +0000157 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000158 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000159 sys.path.append(sitedir) # Add path component
Guido van Rossumf30bec71997-08-29 22:30:45 +0000160 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000161 names = os.listdir(sitedir)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000162 except os.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000163 return
Guido van Rossumf30bec71997-08-29 22:30:45 +0000164 names.sort()
165 for name in names:
Skip Montanaro7a98be22007-08-16 14:35:24 +0000166 if name.endswith(".pth"):
Brett Cannon0096e262004-06-05 01:12:51 +0000167 addpackage(sitedir, name, known_paths)
Fred Drake7f5296e2001-07-20 20:06:17 +0000168 if reset:
Brett Cannon0096e262004-06-05 01:12:51 +0000169 known_paths = None
170 return known_paths
Guido van Rossumf30bec71997-08-29 22:30:45 +0000171
Brett Cannon0096e262004-06-05 01:12:51 +0000172def addsitepackages(known_paths):
173 """Add site-packages (and possibly site-python) to sys.path"""
174 prefixes = [sys.prefix]
175 if sys.exec_prefix != sys.prefix:
176 prefixes.append(sys.exec_prefix)
177 for prefix in prefixes:
178 if prefix:
Skip Montanaro289bc052007-08-17 02:30:27 +0000179 if sys.platform == 'os2emx':
Brett Cannon0096e262004-06-05 01:12:51 +0000180 sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
181 elif os.sep == '/':
182 sitedirs = [os.path.join(prefix,
183 "lib",
184 "python" + sys.version[:3],
185 "site-packages"),
186 os.path.join(prefix, "lib", "site-python")]
187 else:
188 sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
189 if sys.platform == 'darwin':
190 # for framework builds *only* we add the standard Apple
191 # locations. Currently only per-user, but /Library and
192 # /Network/Library could be added too
193 if 'Python.framework' in prefix:
194 home = os.environ.get('HOME')
195 if home:
196 sitedirs.append(
197 os.path.join(home,
198 'Library',
199 'Python',
200 sys.version[:3],
201 'site-packages'))
202 for sitedir in sitedirs:
203 if os.path.isdir(sitedir):
204 addsitedir(sitedir, known_paths)
205 return None
Fred Drake7f5296e2001-07-20 20:06:17 +0000206
Fred Drake1fb5ce02001-07-02 16:55:42 +0000207
Brett Cannon0096e262004-06-05 01:12:51 +0000208def setBEGINLIBPATH():
209 """The OS/2 EMX port has optional extension modules that do double duty
210 as DLLs (and must use the .DLL file extension) for other extensions.
211 The library search path needs to be amended so these will be found
212 during module import. Use BEGINLIBPATH so that these are at the start
213 of the library search path.
Tim Peters4e0e1b62004-07-07 20:54:48 +0000214
Brett Cannon0096e262004-06-05 01:12:51 +0000215 """
Andrew MacIntyre2e8a6e02003-12-02 12:27:25 +0000216 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
217 libpath = os.environ['BEGINLIBPATH'].split(';')
218 if libpath[-1]:
219 libpath.append(dllpath)
220 else:
221 libpath[-1] = dllpath
222 os.environ['BEGINLIBPATH'] = ';'.join(libpath)
223
224
Brett Cannon0096e262004-06-05 01:12:51 +0000225def setquit():
226 """Define new built-ins 'quit' and 'exit'.
227 These are simply strings that display a hint on how to exit.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000228
Brett Cannon0096e262004-06-05 01:12:51 +0000229 """
230 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000231 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000232 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000233 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000234 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000235 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000236
Georg Brandl24cb0532006-03-09 23:22:06 +0000237 class Quitter(object):
238 def __init__(self, name):
239 self.name = name
240 def __repr__(self):
241 return 'Use %s() or %s to exit' % (self.name, eof)
242 def __call__(self, code=None):
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000243 # Shells like IDLE catch the SystemExit, but listen when their
244 # stdin wrapper is closed.
245 try:
Christian Heimes862543a2007-12-31 03:07:24 +0000246 fd = -1
247 if hasattr(sys.stdin, "fileno"):
248 fd = sys.stdin.fileno()
249 if fd != 0:
250 # Don't close stdin if it wraps fd 0
251 sys.stdin.close()
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000252 except:
253 pass
Georg Brandl24cb0532006-03-09 23:22:06 +0000254 raise SystemExit(code)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000255 builtins.quit = Quitter('quit')
256 builtins.exit = Quitter('exit')
Brett Cannon0096e262004-06-05 01:12:51 +0000257
258
259class _Printer(object):
260 """interactive prompt objects for printing the license text, a list of
261 contributors and the copyright notice."""
262
Guido van Rossumd1252392000-09-05 04:39:55 +0000263 MAXLINES = 23
264
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000265 def __init__(self, name, data, files=(), dirs=()):
266 self.__name = name
267 self.__data = data
268 self.__files = files
269 self.__dirs = dirs
270 self.__lines = None
271
272 def __setup(self):
273 if self.__lines:
274 return
275 data = None
276 for dir in self.__dirs:
Brett Cannon0096e262004-06-05 01:12:51 +0000277 for filename in self.__files:
278 filename = os.path.join(dir, filename)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000279 try:
Alex Martelli01c77c62006-08-24 02:58:11 +0000280 fp = open(filename, "rU")
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000281 data = fp.read()
282 fp.close()
283 break
284 except IOError:
285 pass
286 if data:
287 break
288 if not data:
289 data = self.__data
290 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000291 self.__linecnt = len(self.__lines)
292
293 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000294 self.__setup()
295 if len(self.__lines) <= self.MAXLINES:
296 return "\n".join(self.__lines)
297 else:
298 return "Type %s() to see the full %s text" % ((self.__name,)*2)
299
300 def __call__(self):
301 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000302 prompt = 'Hit Return for more, or q (and Return) to quit: '
303 lineno = 0
304 while 1:
305 try:
306 for i in range(lineno, lineno + self.MAXLINES):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000307 print(self.__lines[i])
Guido van Rossumd1252392000-09-05 04:39:55 +0000308 except IndexError:
309 break
310 else:
311 lineno += self.MAXLINES
312 key = None
313 while key is None:
Guido van Rossum704b34d2007-12-20 18:42:56 +0000314 key = input(prompt)
Guido van Rossumd1252392000-09-05 04:39:55 +0000315 if key not in ('', 'q'):
316 key = None
317 if key == 'q':
318 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000319
Brett Cannon0096e262004-06-05 01:12:51 +0000320def setcopyright():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000321 """Set 'copyright' and 'credits' in builtins"""
322 builtins.copyright = _Printer("copyright", sys.copyright)
Brett Cannon0096e262004-06-05 01:12:51 +0000323 if sys.platform[:4] == 'java':
Georg Brandl1a3284e2007-12-02 09:40:06 +0000324 builtins.credits = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000325 "credits",
326 "Jython is maintained by the Jython developers (www.jython.org).")
327 else:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000328 builtins.credits = _Printer("credits", """\
Brett Cannon0096e262004-06-05 01:12:51 +0000329 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
330 for supporting Python development. See www.python.org for more information.""")
331 here = os.path.dirname(os.__file__)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000332 builtins.license = _Printer(
Brett Cannon0096e262004-06-05 01:12:51 +0000333 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
334 ["LICENSE.txt", "LICENSE"],
335 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000336
337
Brett Cannon0096e262004-06-05 01:12:51 +0000338class _Helper(object):
339 """Define the built-in 'help'.
340 This is a wrapper around pydoc.help (with a twist).
Guido van Rossum83213cc2001-06-12 16:48:52 +0000341
Brett Cannon0096e262004-06-05 01:12:51 +0000342 """
343
Guido van Rossum83213cc2001-06-12 16:48:52 +0000344 def __repr__(self):
345 return "Type help() for interactive help, " \
346 "or help(object) for help about object."
347 def __call__(self, *args, **kwds):
348 import pydoc
349 return pydoc.help(*args, **kwds)
350
Brett Cannon0096e262004-06-05 01:12:51 +0000351def sethelper():
Georg Brandl1a3284e2007-12-02 09:40:06 +0000352 builtins.help = _Helper()
Brett Cannon0096e262004-06-05 01:12:51 +0000353
354def aliasmbcs():
355 """On Windows, some default encodings are not provided by Python,
356 while they are always available as "mbcs" in each locale. Make
357 them usable by aliasing to "mbcs" in such a case."""
358 if sys.platform == 'win32':
359 import locale, codecs
360 enc = locale.getdefaultlocale()[1]
361 if enc.startswith('cp'): # "cp***" ?
362 try:
363 codecs.lookup(enc)
364 except LookupError:
365 import encodings
366 encodings._cache[enc] = encodings._unknown
367 encodings.aliases.aliases[enc] = 'mbcs'
368
369def setencoding():
370 """Set the string encoding used by the Unicode implementation. The
371 default is 'ascii', but if you're willing to experiment, you can
372 change this."""
373 encoding = "ascii" # Default value set by _PyUnicode_Init()
374 if 0:
375 # Enable to support locale aware default string encodings.
376 import locale
377 loc = locale.getdefaultlocale()
378 if loc[1]:
379 encoding = loc[1]
380 if 0:
381 # Enable to switch off string to Unicode coercion and implicit
382 # Unicode to string conversion.
383 encoding = "undefined"
384 if encoding != "ascii":
385 # On Non-Unicode builds this will raise an AttributeError...
386 sys.setdefaultencoding(encoding) # Needs Python Unicode build !
Guido van Rossum83213cc2001-06-12 16:48:52 +0000387
388
Brett Cannon0096e262004-06-05 01:12:51 +0000389def execsitecustomize():
390 """Run custom site specific code, if available."""
391 try:
392 import sitecustomize
393 except ImportError:
394 pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000395 except Exception as err:
Guido van Rossumc6fe9832006-08-19 00:10:28 +0000396 if os.environ.get("PYTHONVERBOSE"):
397 raise
398 sys.stderr.write(
399 "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n"
400 "%s: %s\n" %
401 (err.__class__.__name__, err))
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000402
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000403
Brett Cannon0096e262004-06-05 01:12:51 +0000404def main():
405 abs__file__()
406 paths_in_sys = removeduppaths()
407 if (os.name == "posix" and sys.path and
408 os.path.basename(sys.path[-1]) == "Modules"):
409 addbuilddir()
410 paths_in_sys = addsitepackages(paths_in_sys)
411 if sys.platform == 'os2emx':
412 setBEGINLIBPATH()
413 setquit()
414 setcopyright()
415 sethelper()
416 aliasmbcs()
417 setencoding()
418 execsitecustomize()
419 # Remove sys.setdefaultencoding() so that users cannot change the
420 # encoding after initialization. The test for presence is needed when
421 # this module is run as a script, because this code is executed twice.
422 if hasattr(sys, "setdefaultencoding"):
423 del sys.setdefaultencoding
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000424
Brett Cannon0096e262004-06-05 01:12:51 +0000425main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000426
427def _test():
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000428 print("sys.path = [")
Guido van Rossumf30bec71997-08-29 22:30:45 +0000429 for dir in sys.path:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000430 print(" %r," % (dir,))
431 print("]")
Guido van Rossumf30bec71997-08-29 22:30:45 +0000432
433if __name__ == '__main__':
434 _test()