blob: d6e915239ad7f7bd1b42d0844ad2a298a9bd24c7 [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
Nick Coghlanf2b16f32006-06-12 08:23:02 +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
Nick Coghlan3fb55ca2006-06-12 08:19:37 +000018prefixes 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
Neal Norwitz6e482562006-08-15 04:59:30 +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
Neal Norwitz6e482562006-08-15 04:59:30 +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
63import __builtin__
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"""
72 for m in sys.modules.values():
Neal Norwitz0c469852006-04-11 07:21:20 +000073 if hasattr(m, '__loader__'):
Phillip J. Eby47032112006-04-11 01:07:43 +000074 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)
Georg Brandlf00b38e2008-01-21 21:19:07 +0000105 if hasattr(sys, 'gettotalrefcount'):
106 s += '-pydebug'
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000107 s = os.path.join(os.path.dirname(sys.path[-1]), s)
108 sys.path.append(s)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000109
Fred Drake7f5296e2001-07-20 20:06:17 +0000110def _init_pathinfo():
Brett Cannon0096e262004-06-05 01:12:51 +0000111 """Return a set containing all existing directory entries from sys.path"""
112 d = set()
Fred Drake7f5296e2001-07-20 20:06:17 +0000113 for dir in sys.path:
Brett Cannon0096e262004-06-05 01:12:51 +0000114 try:
115 if os.path.isdir(dir):
116 dir, dircase = makepath(dir)
117 d.add(dircase)
118 except TypeError:
Fred Drake7f5296e2001-07-20 20:06:17 +0000119 continue
Brett Cannon0096e262004-06-05 01:12:51 +0000120 return d
Fred Drake7f5296e2001-07-20 20:06:17 +0000121
Brett Cannon0096e262004-06-05 01:12:51 +0000122def addpackage(sitedir, name, known_paths):
Georg Brandl8d76cca2007-05-19 18:09:26 +0000123 """Process a .pth file within the site-packages directory:
124 For each line in the file, either combine it with sitedir to a path
125 and add that to known_paths, or execute it if it starts with 'import '.
126 """
Brett Cannon0096e262004-06-05 01:12:51 +0000127 if known_paths is None:
Fred Drake7f5296e2001-07-20 20:06:17 +0000128 _init_pathinfo()
129 reset = 1
130 else:
131 reset = 0
Brett Cannon0096e262004-06-05 01:12:51 +0000132 fullname = os.path.join(sitedir, name)
133 try:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000134 f = open(fullname, "rU")
Brett Cannon0096e262004-06-05 01:12:51 +0000135 except IOError:
136 return
137 try:
138 for line in f:
139 if line.startswith("#"):
140 continue
Martin v. Löwis2681beb2007-03-12 11:01:10 +0000141 if line.startswith("import ") or line.startswith("import\t"):
Brett Cannon0096e262004-06-05 01:12:51 +0000142 exec line
143 continue
144 line = line.rstrip()
145 dir, dircase = makepath(sitedir, line)
146 if not dircase in known_paths and os.path.exists(dir):
147 sys.path.append(dir)
148 known_paths.add(dircase)
149 finally:
150 f.close()
151 if reset:
152 known_paths = None
153 return known_paths
154
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000155def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000156 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
157 'sitedir'"""
158 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000159 known_paths = _init_pathinfo()
Brett Cannon0096e262004-06-05 01:12:51 +0000160 reset = 1
161 else:
162 reset = 0
Fred Drake1fb5ce02001-07-02 16:55:42 +0000163 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000164 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000165 sys.path.append(sitedir) # Add path component
Guido van Rossumf30bec71997-08-29 22:30:45 +0000166 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000167 names = os.listdir(sitedir)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000168 except os.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000169 return
Guido van Rossumf30bec71997-08-29 22:30:45 +0000170 names.sort()
171 for name in names:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000172 if name.endswith(os.extsep + "pth"):
Brett Cannon0096e262004-06-05 01:12:51 +0000173 addpackage(sitedir, name, known_paths)
Fred Drake7f5296e2001-07-20 20:06:17 +0000174 if reset:
Brett Cannon0096e262004-06-05 01:12:51 +0000175 known_paths = None
176 return known_paths
Guido van Rossumf30bec71997-08-29 22:30:45 +0000177
Brett Cannon0096e262004-06-05 01:12:51 +0000178def addsitepackages(known_paths):
179 """Add site-packages (and possibly site-python) to sys.path"""
180 prefixes = [sys.prefix]
181 if sys.exec_prefix != sys.prefix:
182 prefixes.append(sys.exec_prefix)
183 for prefix in prefixes:
184 if prefix:
185 if sys.platform in ('os2emx', 'riscos'):
186 sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
187 elif os.sep == '/':
188 sitedirs = [os.path.join(prefix,
189 "lib",
190 "python" + sys.version[:3],
191 "site-packages"),
192 os.path.join(prefix, "lib", "site-python")]
193 else:
194 sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
195 if sys.platform == 'darwin':
196 # for framework builds *only* we add the standard Apple
197 # locations. Currently only per-user, but /Library and
198 # /Network/Library could be added too
199 if 'Python.framework' in prefix:
200 home = os.environ.get('HOME')
201 if home:
202 sitedirs.append(
203 os.path.join(home,
204 'Library',
205 'Python',
206 sys.version[:3],
207 'site-packages'))
208 for sitedir in sitedirs:
209 if os.path.isdir(sitedir):
210 addsitedir(sitedir, known_paths)
211 return None
Fred Drake7f5296e2001-07-20 20:06:17 +0000212
Fred Drake1fb5ce02001-07-02 16:55:42 +0000213
Brett Cannon0096e262004-06-05 01:12:51 +0000214def setBEGINLIBPATH():
215 """The OS/2 EMX port has optional extension modules that do double duty
216 as DLLs (and must use the .DLL file extension) for other extensions.
217 The library search path needs to be amended so these will be found
218 during module import. Use BEGINLIBPATH so that these are at the start
219 of the library search path.
Tim Peters4e0e1b62004-07-07 20:54:48 +0000220
Brett Cannon0096e262004-06-05 01:12:51 +0000221 """
Andrew MacIntyre2e8a6e02003-12-02 12:27:25 +0000222 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
223 libpath = os.environ['BEGINLIBPATH'].split(';')
224 if libpath[-1]:
225 libpath.append(dllpath)
226 else:
227 libpath[-1] = dllpath
228 os.environ['BEGINLIBPATH'] = ';'.join(libpath)
229
230
Brett Cannon0096e262004-06-05 01:12:51 +0000231def setquit():
232 """Define new built-ins 'quit' and 'exit'.
233 These are simply strings that display a hint on how to exit.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000234
Brett Cannon0096e262004-06-05 01:12:51 +0000235 """
236 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000237 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000238 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000239 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000240 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000241 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000242
Georg Brandl24cb0532006-03-09 23:22:06 +0000243 class Quitter(object):
244 def __init__(self, name):
245 self.name = name
246 def __repr__(self):
247 return 'Use %s() or %s to exit' % (self.name, eof)
248 def __call__(self, code=None):
Kurt B. Kaiserd112bc72006-08-16 05:01:42 +0000249 # Shells like IDLE catch the SystemExit, but listen when their
250 # stdin wrapper is closed.
251 try:
252 sys.stdin.close()
253 except:
254 pass
Georg Brandl24cb0532006-03-09 23:22:06 +0000255 raise SystemExit(code)
256 __builtin__.quit = Quitter('quit')
257 __builtin__.exit = Quitter('exit')
Brett Cannon0096e262004-06-05 01:12:51 +0000258
259
260class _Printer(object):
261 """interactive prompt objects for printing the license text, a list of
262 contributors and the copyright notice."""
263
Guido van Rossumd1252392000-09-05 04:39:55 +0000264 MAXLINES = 23
265
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000266 def __init__(self, name, data, files=(), dirs=()):
267 self.__name = name
268 self.__data = data
269 self.__files = files
270 self.__dirs = dirs
271 self.__lines = None
272
273 def __setup(self):
274 if self.__lines:
275 return
276 data = None
277 for dir in self.__dirs:
Brett Cannon0096e262004-06-05 01:12:51 +0000278 for filename in self.__files:
279 filename = os.path.join(dir, filename)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000280 try:
Brett Cannon0096e262004-06-05 01:12:51 +0000281 fp = file(filename, "rU")
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000282 data = fp.read()
283 fp.close()
284 break
285 except IOError:
286 pass
287 if data:
288 break
289 if not data:
290 data = self.__data
291 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000292 self.__linecnt = len(self.__lines)
293
294 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000295 self.__setup()
296 if len(self.__lines) <= self.MAXLINES:
297 return "\n".join(self.__lines)
298 else:
299 return "Type %s() to see the full %s text" % ((self.__name,)*2)
300
301 def __call__(self):
302 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000303 prompt = 'Hit Return for more, or q (and Return) to quit: '
304 lineno = 0
305 while 1:
306 try:
307 for i in range(lineno, lineno + self.MAXLINES):
308 print self.__lines[i]
309 except IndexError:
310 break
311 else:
312 lineno += self.MAXLINES
313 key = None
314 while key is None:
315 key = raw_input(prompt)
316 if key not in ('', 'q'):
317 key = None
318 if key == 'q':
319 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000320
Brett Cannon0096e262004-06-05 01:12:51 +0000321def setcopyright():
322 """Set 'copyright' and 'credits' in __builtin__"""
323 __builtin__.copyright = _Printer("copyright", sys.copyright)
324 if sys.platform[:4] == 'java':
325 __builtin__.credits = _Printer(
326 "credits",
327 "Jython is maintained by the Jython developers (www.jython.org).")
328 else:
329 __builtin__.credits = _Printer("credits", """\
330 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
331 for supporting Python development. See www.python.org for more information.""")
332 here = os.path.dirname(os.__file__)
333 __builtin__.license = _Printer(
334 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
335 ["LICENSE.txt", "LICENSE"],
336 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000337
338
Brett Cannon0096e262004-06-05 01:12:51 +0000339class _Helper(object):
340 """Define the built-in 'help'.
341 This is a wrapper around pydoc.help (with a twist).
Guido van Rossum83213cc2001-06-12 16:48:52 +0000342
Brett Cannon0096e262004-06-05 01:12:51 +0000343 """
344
Guido van Rossum83213cc2001-06-12 16:48:52 +0000345 def __repr__(self):
346 return "Type help() for interactive help, " \
347 "or help(object) for help about object."
348 def __call__(self, *args, **kwds):
349 import pydoc
350 return pydoc.help(*args, **kwds)
351
Brett Cannon0096e262004-06-05 01:12:51 +0000352def sethelper():
353 __builtin__.help = _Helper()
354
355def aliasmbcs():
356 """On Windows, some default encodings are not provided by Python,
357 while they are always available as "mbcs" in each locale. Make
358 them usable by aliasing to "mbcs" in such a case."""
359 if sys.platform == 'win32':
360 import locale, codecs
361 enc = locale.getdefaultlocale()[1]
362 if enc.startswith('cp'): # "cp***" ?
363 try:
364 codecs.lookup(enc)
365 except LookupError:
366 import encodings
367 encodings._cache[enc] = encodings._unknown
368 encodings.aliases.aliases[enc] = 'mbcs'
369
370def setencoding():
371 """Set the string encoding used by the Unicode implementation. The
372 default is 'ascii', but if you're willing to experiment, you can
373 change this."""
374 encoding = "ascii" # Default value set by _PyUnicode_Init()
375 if 0:
376 # Enable to support locale aware default string encodings.
377 import locale
378 loc = locale.getdefaultlocale()
379 if loc[1]:
380 encoding = loc[1]
381 if 0:
382 # Enable to switch off string to Unicode coercion and implicit
383 # Unicode to string conversion.
384 encoding = "undefined"
385 if encoding != "ascii":
386 # On Non-Unicode builds this will raise an AttributeError...
387 sys.setdefaultencoding(encoding) # Needs Python Unicode build !
Guido van Rossum83213cc2001-06-12 16:48:52 +0000388
389
Brett Cannon0096e262004-06-05 01:12:51 +0000390def execsitecustomize():
391 """Run custom site specific code, if available."""
392 try:
393 import sitecustomize
394 except ImportError:
395 pass
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000396
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000397
Brett Cannon0096e262004-06-05 01:12:51 +0000398def main():
399 abs__file__()
400 paths_in_sys = removeduppaths()
401 if (os.name == "posix" and sys.path and
402 os.path.basename(sys.path[-1]) == "Modules"):
403 addbuilddir()
404 paths_in_sys = addsitepackages(paths_in_sys)
405 if sys.platform == 'os2emx':
406 setBEGINLIBPATH()
407 setquit()
408 setcopyright()
409 sethelper()
410 aliasmbcs()
411 setencoding()
412 execsitecustomize()
413 # Remove sys.setdefaultencoding() so that users cannot change the
414 # encoding after initialization. The test for presence is needed when
415 # this module is run as a script, because this code is executed twice.
416 if hasattr(sys, "setdefaultencoding"):
417 del sys.setdefaultencoding
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000418
Brett Cannon0096e262004-06-05 01:12:51 +0000419main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000420
421def _test():
422 print "sys.path = ["
423 for dir in sys.path:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000424 print " %r," % (dir,)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000425 print "]"
426
427if __name__ == '__main__':
428 _test()