blob: 80749797e000626f5ca4f9e6f506322990f6991d [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
Guido van Rossum0d8fcb21998-01-13 18:32:40 +000014Unix, it starts with sys.prefix and sys.exec_prefix (if different) and
15appends lib/python<version>/site-packages as well as lib/site-python.
16On other platforms (mainly Mac and Windows), it uses just sys.prefix
Barry Warsaw6e1c5762001-12-17 15:40:24 +000017(and sys.exec_prefix, if different, but this is unlikely). The
Guido van Rossum62b297b1997-09-08 02:14:09 +000018resulting directories, if they exist, are appended to sys.path, and
19also inspected for path configuration files.
Guido van Rossume57c96e1996-08-17 19:56:26 +000020
Guido van Rossumf30bec71997-08-29 22:30:45 +000021A path configuration file is a file whose name has the form
22<package>.pth; its contents are additional directories (one per line)
23to be added to sys.path. Non-existing directories (or
24non-directories) are never added to sys.path; no directory is added to
25sys.path more than once. Blank lines and lines beginning with
Guido van Rossumfacf24b2001-12-17 16:07:06 +000026'#' are skipped. Lines starting with 'import' are executed.
Guido van Rossume57c96e1996-08-17 19:56:26 +000027
Guido van Rossumf30bec71997-08-29 22:30:45 +000028For example, suppose sys.prefix and sys.exec_prefix are set to
Guido van Rossume7201761998-11-25 15:57:47 +000029/usr/local and there is a directory /usr/local/lib/python1.5/site-packages
Guido van Rossum62b297b1997-09-08 02:14:09 +000030with three subdirectories, foo, bar and spam, and two path
31configuration files, foo.pth and bar.pth. Assume foo.pth contains the
32following:
Guido van Rossumf30bec71997-08-29 22:30:45 +000033
34 # foo package configuration
35 foo
36 bar
37 bletch
38
39and bar.pth contains:
40
41 # bar package configuration
42 bar
43
44Then the following directories are added to sys.path, in this order:
45
Guido van Rossum62b297b1997-09-08 02:14:09 +000046 /usr/local/lib/python1.5/site-packages/bar
47 /usr/local/lib/python1.5/site-packages/foo
Guido van Rossumf30bec71997-08-29 22:30:45 +000048
49Note that bletch is omitted because it doesn't exist; bar precedes foo
50because bar.pth comes alphabetically before foo.pth; and spam is
51omitted because it is not mentioned in either path configuration file.
Guido van Rossume57c96e1996-08-17 19:56:26 +000052
53After these path manipulations, an attempt is made to import a module
Guido van Rossumf30bec71997-08-29 22:30:45 +000054named sitecustomize, which can perform arbitrary additional
55site-specific customizations. If this import fails with an
56ImportError exception, it is silently ignored.
Guido van Rossume57c96e1996-08-17 19:56:26 +000057
Guido van Rossume57c96e1996-08-17 19:56:26 +000058"""
59
Brett Cannon0096e262004-06-05 01:12:51 +000060import sys
61import os
62import __builtin__
Guido van Rossume57c96e1996-08-17 19:56:26 +000063
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000064
Fred Drake38cb9f12000-09-28 16:52:36 +000065def makepath(*paths):
Fred Drake1fb5ce02001-07-02 16:55:42 +000066 dir = os.path.abspath(os.path.join(*paths))
67 return dir, os.path.normcase(dir)
Fred Drake38cb9f12000-09-28 16:52:36 +000068
Brett Cannon0096e262004-06-05 01:12:51 +000069def abs__file__():
70 """Set all module' __file__ attribute to an absolute path"""
71 for m in sys.modules.values():
Phillip J. Eby47032112006-04-11 01:07:43 +000072 if hasattr(m,'__loader__'):
73 continue # don't mess with a PEP 302-supplied __file__
Brett Cannon0096e262004-06-05 01:12:51 +000074 try:
75 m.__file__ = os.path.abspath(m.__file__)
76 except AttributeError:
77 continue
Fred Drake38cb9f12000-09-28 16:52:36 +000078
Brett Cannon0096e262004-06-05 01:12:51 +000079def removeduppaths():
80 """ Remove duplicate entries from sys.path along with making them
81 absolute"""
82 # This ensures that the initial path provided by the interpreter contains
83 # only absolute pathnames, even if we're running from the build directory.
84 L = []
85 known_paths = set()
86 for dir in sys.path:
87 # Filter out duplicate paths (on case-insensitive file systems also
88 # if they only differ in case); turn relative paths into absolute
89 # paths.
90 dir, dircase = makepath(dir)
91 if not dircase in known_paths:
92 L.append(dir)
93 known_paths.add(dircase)
94 sys.path[:] = L
95 return known_paths
Fred Drake38cb9f12000-09-28 16:52:36 +000096
Fred Drakee80c0d32002-07-25 20:13:03 +000097# XXX This should not be part of site.py, since it is needed even when
98# using the -S option for Python. See http://www.python.org/sf/586680
Brett Cannon0096e262004-06-05 01:12:51 +000099def addbuilddir():
100 """Append ./build/lib.<platform> in case we're running in the build dir
101 (especially for Guido :-)"""
Jeremy Hylton6d58bf62003-07-18 17:45:33 +0000102 from distutils.util import get_platform
103 s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000104 s = os.path.join(os.path.dirname(sys.path[-1]), s)
105 sys.path.append(s)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000106
Fred Drake7f5296e2001-07-20 20:06:17 +0000107def _init_pathinfo():
Brett Cannon0096e262004-06-05 01:12:51 +0000108 """Return a set containing all existing directory entries from sys.path"""
109 d = set()
Fred Drake7f5296e2001-07-20 20:06:17 +0000110 for dir in sys.path:
Brett Cannon0096e262004-06-05 01:12:51 +0000111 try:
112 if os.path.isdir(dir):
113 dir, dircase = makepath(dir)
114 d.add(dircase)
115 except TypeError:
Fred Drake7f5296e2001-07-20 20:06:17 +0000116 continue
Brett Cannon0096e262004-06-05 01:12:51 +0000117 return d
Fred Drake7f5296e2001-07-20 20:06:17 +0000118
Brett Cannon0096e262004-06-05 01:12:51 +0000119def addpackage(sitedir, name, known_paths):
120 """Add a new path to known_paths by combining sitedir and 'name' or execute
121 sitedir if it starts with 'import'"""
122 if known_paths is None:
Fred Drake7f5296e2001-07-20 20:06:17 +0000123 _init_pathinfo()
124 reset = 1
125 else:
126 reset = 0
Brett Cannon0096e262004-06-05 01:12:51 +0000127 fullname = os.path.join(sitedir, name)
128 try:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000129 f = open(fullname, "rU")
Brett Cannon0096e262004-06-05 01:12:51 +0000130 except IOError:
131 return
132 try:
133 for line in f:
134 if line.startswith("#"):
135 continue
136 if line.startswith("import"):
137 exec line
138 continue
139 line = line.rstrip()
140 dir, dircase = makepath(sitedir, line)
141 if not dircase in known_paths and os.path.exists(dir):
142 sys.path.append(dir)
143 known_paths.add(dircase)
144 finally:
145 f.close()
146 if reset:
147 known_paths = None
148 return known_paths
149
Brett Cannon12f8c4d2004-07-09 23:38:18 +0000150def addsitedir(sitedir, known_paths=None):
Brett Cannon0096e262004-06-05 01:12:51 +0000151 """Add 'sitedir' argument to sys.path if missing and handle .pth files in
152 'sitedir'"""
153 if known_paths is None:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000154 known_paths = _init_pathinfo()
Brett Cannon0096e262004-06-05 01:12:51 +0000155 reset = 1
156 else:
157 reset = 0
Fred Drake1fb5ce02001-07-02 16:55:42 +0000158 sitedir, sitedircase = makepath(sitedir)
Brett Cannon0096e262004-06-05 01:12:51 +0000159 if not sitedircase in known_paths:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000160 sys.path.append(sitedir) # Add path component
Guido van Rossumf30bec71997-08-29 22:30:45 +0000161 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000162 names = os.listdir(sitedir)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000163 except os.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000164 return
Guido van Rossumf30bec71997-08-29 22:30:45 +0000165 names.sort()
166 for name in names:
Brett Cannon4d0bddf2004-07-20 02:28:28 +0000167 if name.endswith(os.extsep + "pth"):
Brett Cannon0096e262004-06-05 01:12:51 +0000168 addpackage(sitedir, name, known_paths)
Fred Drake7f5296e2001-07-20 20:06:17 +0000169 if reset:
Brett Cannon0096e262004-06-05 01:12:51 +0000170 known_paths = None
171 return known_paths
Guido van Rossumf30bec71997-08-29 22:30:45 +0000172
Brett Cannon0096e262004-06-05 01:12:51 +0000173def addsitepackages(known_paths):
174 """Add site-packages (and possibly site-python) to sys.path"""
175 prefixes = [sys.prefix]
176 if sys.exec_prefix != sys.prefix:
177 prefixes.append(sys.exec_prefix)
178 for prefix in prefixes:
179 if prefix:
180 if sys.platform in ('os2emx', 'riscos'):
181 sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
182 elif os.sep == '/':
183 sitedirs = [os.path.join(prefix,
184 "lib",
185 "python" + sys.version[:3],
186 "site-packages"),
187 os.path.join(prefix, "lib", "site-python")]
188 else:
189 sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
190 if sys.platform == 'darwin':
191 # for framework builds *only* we add the standard Apple
192 # locations. Currently only per-user, but /Library and
193 # /Network/Library could be added too
194 if 'Python.framework' in prefix:
195 home = os.environ.get('HOME')
196 if home:
197 sitedirs.append(
198 os.path.join(home,
199 'Library',
200 'Python',
201 sys.version[:3],
202 'site-packages'))
203 for sitedir in sitedirs:
204 if os.path.isdir(sitedir):
205 addsitedir(sitedir, known_paths)
206 return None
Fred Drake7f5296e2001-07-20 20:06:17 +0000207
Fred Drake1fb5ce02001-07-02 16:55:42 +0000208
Brett Cannon0096e262004-06-05 01:12:51 +0000209def setBEGINLIBPATH():
210 """The OS/2 EMX port has optional extension modules that do double duty
211 as DLLs (and must use the .DLL file extension) for other extensions.
212 The library search path needs to be amended so these will be found
213 during module import. Use BEGINLIBPATH so that these are at the start
214 of the library search path.
Tim Peters4e0e1b62004-07-07 20:54:48 +0000215
Brett Cannon0096e262004-06-05 01:12:51 +0000216 """
Andrew MacIntyre2e8a6e02003-12-02 12:27:25 +0000217 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
218 libpath = os.environ['BEGINLIBPATH'].split(';')
219 if libpath[-1]:
220 libpath.append(dllpath)
221 else:
222 libpath[-1] = dllpath
223 os.environ['BEGINLIBPATH'] = ';'.join(libpath)
224
225
Brett Cannon0096e262004-06-05 01:12:51 +0000226def setquit():
227 """Define new built-ins 'quit' and 'exit'.
228 These are simply strings that display a hint on how to exit.
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000229
Brett Cannon0096e262004-06-05 01:12:51 +0000230 """
231 if os.sep == ':':
Georg Brandl24cb0532006-03-09 23:22:06 +0000232 eof = 'Cmd-Q'
Brett Cannon0096e262004-06-05 01:12:51 +0000233 elif os.sep == '\\':
Georg Brandl24cb0532006-03-09 23:22:06 +0000234 eof = 'Ctrl-Z plus Return'
Brett Cannon0096e262004-06-05 01:12:51 +0000235 else:
Georg Brandl24cb0532006-03-09 23:22:06 +0000236 eof = 'Ctrl-D (i.e. EOF)'
Tim Peters88ca4672006-03-10 23:39:56 +0000237
Georg Brandl24cb0532006-03-09 23:22:06 +0000238 class Quitter(object):
239 def __init__(self, name):
240 self.name = name
241 def __repr__(self):
242 return 'Use %s() or %s to exit' % (self.name, eof)
243 def __call__(self, code=None):
244 raise SystemExit(code)
245 __builtin__.quit = Quitter('quit')
246 __builtin__.exit = Quitter('exit')
Brett Cannon0096e262004-06-05 01:12:51 +0000247
248
249class _Printer(object):
250 """interactive prompt objects for printing the license text, a list of
251 contributors and the copyright notice."""
252
Guido van Rossumd1252392000-09-05 04:39:55 +0000253 MAXLINES = 23
254
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000255 def __init__(self, name, data, files=(), dirs=()):
256 self.__name = name
257 self.__data = data
258 self.__files = files
259 self.__dirs = dirs
260 self.__lines = None
261
262 def __setup(self):
263 if self.__lines:
264 return
265 data = None
266 for dir in self.__dirs:
Brett Cannon0096e262004-06-05 01:12:51 +0000267 for filename in self.__files:
268 filename = os.path.join(dir, filename)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000269 try:
Brett Cannon0096e262004-06-05 01:12:51 +0000270 fp = file(filename, "rU")
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000271 data = fp.read()
272 fp.close()
273 break
274 except IOError:
275 pass
276 if data:
277 break
278 if not data:
279 data = self.__data
280 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000281 self.__linecnt = len(self.__lines)
282
283 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000284 self.__setup()
285 if len(self.__lines) <= self.MAXLINES:
286 return "\n".join(self.__lines)
287 else:
288 return "Type %s() to see the full %s text" % ((self.__name,)*2)
289
290 def __call__(self):
291 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000292 prompt = 'Hit Return for more, or q (and Return) to quit: '
293 lineno = 0
294 while 1:
295 try:
296 for i in range(lineno, lineno + self.MAXLINES):
297 print self.__lines[i]
298 except IndexError:
299 break
300 else:
301 lineno += self.MAXLINES
302 key = None
303 while key is None:
304 key = raw_input(prompt)
305 if key not in ('', 'q'):
306 key = None
307 if key == 'q':
308 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000309
Brett Cannon0096e262004-06-05 01:12:51 +0000310def setcopyright():
311 """Set 'copyright' and 'credits' in __builtin__"""
312 __builtin__.copyright = _Printer("copyright", sys.copyright)
313 if sys.platform[:4] == 'java':
314 __builtin__.credits = _Printer(
315 "credits",
316 "Jython is maintained by the Jython developers (www.jython.org).")
317 else:
318 __builtin__.credits = _Printer("credits", """\
319 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
320 for supporting Python development. See www.python.org for more information.""")
321 here = os.path.dirname(os.__file__)
322 __builtin__.license = _Printer(
323 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
324 ["LICENSE.txt", "LICENSE"],
325 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000326
327
Brett Cannon0096e262004-06-05 01:12:51 +0000328class _Helper(object):
329 """Define the built-in 'help'.
330 This is a wrapper around pydoc.help (with a twist).
Guido van Rossum83213cc2001-06-12 16:48:52 +0000331
Brett Cannon0096e262004-06-05 01:12:51 +0000332 """
333
Guido van Rossum83213cc2001-06-12 16:48:52 +0000334 def __repr__(self):
335 return "Type help() for interactive help, " \
336 "or help(object) for help about object."
337 def __call__(self, *args, **kwds):
338 import pydoc
339 return pydoc.help(*args, **kwds)
340
Brett Cannon0096e262004-06-05 01:12:51 +0000341def sethelper():
342 __builtin__.help = _Helper()
343
344def aliasmbcs():
345 """On Windows, some default encodings are not provided by Python,
346 while they are always available as "mbcs" in each locale. Make
347 them usable by aliasing to "mbcs" in such a case."""
348 if sys.platform == 'win32':
349 import locale, codecs
350 enc = locale.getdefaultlocale()[1]
351 if enc.startswith('cp'): # "cp***" ?
352 try:
353 codecs.lookup(enc)
354 except LookupError:
355 import encodings
356 encodings._cache[enc] = encodings._unknown
357 encodings.aliases.aliases[enc] = 'mbcs'
358
359def setencoding():
360 """Set the string encoding used by the Unicode implementation. The
361 default is 'ascii', but if you're willing to experiment, you can
362 change this."""
363 encoding = "ascii" # Default value set by _PyUnicode_Init()
364 if 0:
365 # Enable to support locale aware default string encodings.
366 import locale
367 loc = locale.getdefaultlocale()
368 if loc[1]:
369 encoding = loc[1]
370 if 0:
371 # Enable to switch off string to Unicode coercion and implicit
372 # Unicode to string conversion.
373 encoding = "undefined"
374 if encoding != "ascii":
375 # On Non-Unicode builds this will raise an AttributeError...
376 sys.setdefaultencoding(encoding) # Needs Python Unicode build !
Guido van Rossum83213cc2001-06-12 16:48:52 +0000377
378
Brett Cannon0096e262004-06-05 01:12:51 +0000379def execsitecustomize():
380 """Run custom site specific code, if available."""
381 try:
382 import sitecustomize
383 except ImportError:
384 pass
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000385
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000386
Brett Cannon0096e262004-06-05 01:12:51 +0000387def main():
388 abs__file__()
389 paths_in_sys = removeduppaths()
390 if (os.name == "posix" and sys.path and
391 os.path.basename(sys.path[-1]) == "Modules"):
392 addbuilddir()
393 paths_in_sys = addsitepackages(paths_in_sys)
394 if sys.platform == 'os2emx':
395 setBEGINLIBPATH()
396 setquit()
397 setcopyright()
398 sethelper()
399 aliasmbcs()
400 setencoding()
401 execsitecustomize()
402 # Remove sys.setdefaultencoding() so that users cannot change the
403 # encoding after initialization. The test for presence is needed when
404 # this module is run as a script, because this code is executed twice.
405 if hasattr(sys, "setdefaultencoding"):
406 del sys.setdefaultencoding
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000407
Brett Cannon0096e262004-06-05 01:12:51 +0000408main()
Guido van Rossumf30bec71997-08-29 22:30:45 +0000409
410def _test():
411 print "sys.path = ["
412 for dir in sys.path:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000413 print " %r," % (dir,)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000414 print "]"
415
416if __name__ == '__main__':
417 _test()