blob: 3e93a07e5244c7791971917e1f54b3378367d04b [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
Guido van Rossum0d8fcb21998-01-13 18:32:40 +000013This will append site-specific paths to to the module search path. On
14Unix, 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
60import sys, os
61
Guido van Rossumd74fb6b2001-03-02 06:43:49 +000062
Fred Drake38cb9f12000-09-28 16:52:36 +000063def makepath(*paths):
Fred Drake1fb5ce02001-07-02 16:55:42 +000064 dir = os.path.abspath(os.path.join(*paths))
65 return dir, os.path.normcase(dir)
Fred Drake38cb9f12000-09-28 16:52:36 +000066
Fred Drake1fb5ce02001-07-02 16:55:42 +000067for m in sys.modules.values():
Barry Warsaw62d24882001-03-23 17:53:49 +000068 if hasattr(m, "__file__") and m.__file__:
Fred Drake1fb5ce02001-07-02 16:55:42 +000069 m.__file__ = os.path.abspath(m.__file__)
70del m
Fred Drake38cb9f12000-09-28 16:52:36 +000071
72# This ensures that the initial path provided by the interpreter contains
73# only absolute pathnames, even if we're running from the build directory.
74L = []
Fred Drake7f5296e2001-07-20 20:06:17 +000075_dirs_in_sys_path = {}
Just van Rossum52e14d62002-12-30 22:08:05 +000076dir = dircase = None # sys.path may be empty at this point
Fred Drake38cb9f12000-09-28 16:52:36 +000077for dir in sys.path:
Just van Rossum52e14d62002-12-30 22:08:05 +000078 # Filter out duplicate paths (on case-insensitive file systems also
79 # if they only differ in case); turn relative paths into absolute
80 # paths.
Fred Drake1fb5ce02001-07-02 16:55:42 +000081 dir, dircase = makepath(dir)
Raymond Hettinger54f02222002-06-01 14:18:47 +000082 if not dircase in _dirs_in_sys_path:
Fred Drake38cb9f12000-09-28 16:52:36 +000083 L.append(dir)
Fred Drake7f5296e2001-07-20 20:06:17 +000084 _dirs_in_sys_path[dircase] = 1
Fred Drake38cb9f12000-09-28 16:52:36 +000085sys.path[:] = L
Neal Norwitz34172d52002-02-11 18:34:41 +000086del dir, dircase, L
Fred Drake38cb9f12000-09-28 16:52:36 +000087
Guido van Rossum48eb9cd2001-01-19 21:54:59 +000088# Append ./build/lib.<platform> in case we're running in the build dir
89# (especially for Guido :-)
Fred Drakee80c0d32002-07-25 20:13:03 +000090# XXX This should not be part of site.py, since it is needed even when
91# using the -S option for Python. See http://www.python.org/sf/586680
Tim Peters230a60c2002-11-09 05:08:07 +000092if (os.name == "posix" and sys.path and
Marc-André Lemburg7ccd30f2002-09-19 11:11:27 +000093 os.path.basename(sys.path[-1]) == "Modules"):
Jeremy Hyltonbdf3b502003-07-18 17:24:07 +000094 s = "build/lib.%s-%.3s" % ("linux-i686", sys.version)
Guido van Rossum48eb9cd2001-01-19 21:54:59 +000095 s = os.path.join(os.path.dirname(sys.path[-1]), s)
96 sys.path.append(s)
Jeremy Hyltonbdf3b502003-07-18 17:24:07 +000097##if (os.name == "posix" and sys.path and
98## os.path.basename(sys.path[-1]) == "Modules"):
99## from distutils.util import get_platform
100## s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
101## s = os.path.join(os.path.dirname(sys.path[-1]), s)
102## sys.path.append(s)
103## del get_platform, s
Guido van Rossum48eb9cd2001-01-19 21:54:59 +0000104
Fred Drake7f5296e2001-07-20 20:06:17 +0000105def _init_pathinfo():
106 global _dirs_in_sys_path
107 _dirs_in_sys_path = d = {}
108 for dir in sys.path:
109 if dir and not os.path.isdir(dir):
110 continue
111 dir, dircase = makepath(dir)
112 d[dircase] = 1
113
Guido van Rossumf30bec71997-08-29 22:30:45 +0000114def addsitedir(sitedir):
Fred Drake7f5296e2001-07-20 20:06:17 +0000115 global _dirs_in_sys_path
116 if _dirs_in_sys_path is None:
117 _init_pathinfo()
118 reset = 1
119 else:
120 reset = 0
Fred Drake1fb5ce02001-07-02 16:55:42 +0000121 sitedir, sitedircase = makepath(sitedir)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000122 if not sitedircase in _dirs_in_sys_path:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000123 sys.path.append(sitedir) # Add path component
Guido van Rossumf30bec71997-08-29 22:30:45 +0000124 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000125 names = os.listdir(sitedir)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000126 except os.error:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000127 return
Guido van Rossumf30bec71997-08-29 22:30:45 +0000128 names.sort()
129 for name in names:
Guido van Rossume2ae77b2001-10-24 20:42:55 +0000130 if name[-4:] == os.extsep + "pth":
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000131 addpackage(sitedir, name)
Fred Drake7f5296e2001-07-20 20:06:17 +0000132 if reset:
133 _dirs_in_sys_path = None
Guido van Rossumf30bec71997-08-29 22:30:45 +0000134
135def addpackage(sitedir, name):
Fred Drake7f5296e2001-07-20 20:06:17 +0000136 global _dirs_in_sys_path
137 if _dirs_in_sys_path is None:
138 _init_pathinfo()
139 reset = 1
140 else:
141 reset = 0
Guido van Rossumf30bec71997-08-29 22:30:45 +0000142 fullname = os.path.join(sitedir, name)
143 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000144 f = open(fullname)
Guido van Rossumf30bec71997-08-29 22:30:45 +0000145 except IOError:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000146 return
Guido van Rossumf30bec71997-08-29 22:30:45 +0000147 while 1:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000148 dir = f.readline()
149 if not dir:
150 break
151 if dir[0] == '#':
152 continue
Martin v. Löwisbb0a4b72001-01-11 13:02:43 +0000153 if dir.startswith("import"):
154 exec dir
155 continue
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000156 if dir[-1] == '\n':
157 dir = dir[:-1]
Fred Drake1fb5ce02001-07-02 16:55:42 +0000158 dir, dircase = makepath(sitedir, dir)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000159 if not dircase in _dirs_in_sys_path and os.path.exists(dir):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000160 sys.path.append(dir)
Fred Drake7f5296e2001-07-20 20:06:17 +0000161 _dirs_in_sys_path[dircase] = 1
162 if reset:
163 _dirs_in_sys_path = None
Guido van Rossumf30bec71997-08-29 22:30:45 +0000164
165prefixes = [sys.prefix]
Jeremy Hyltonbdf3b502003-07-18 17:24:07 +0000166sitedir = None # make sure sitedir is initialized because of later 'del'
Guido van Rossumf30bec71997-08-29 22:30:45 +0000167if sys.exec_prefix != sys.prefix:
168 prefixes.append(sys.exec_prefix)
169for prefix in prefixes:
Guido van Rossume57c96e1996-08-17 19:56:26 +0000170 if prefix:
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000171 if sys.platform in ('os2emx', 'riscos'):
Andrew MacIntyre5cef5712002-02-24 05:32:32 +0000172 sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
173 elif os.sep == '/':
Fred Drake1fb5ce02001-07-02 16:55:42 +0000174 sitedirs = [os.path.join(prefix,
175 "lib",
176 "python" + sys.version[:3],
177 "site-packages"),
178 os.path.join(prefix, "lib", "site-python")]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000179 else:
Tim Peters6a479f52001-07-12 05:20:13 +0000180 sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
Jack Jansenbe5d7072003-04-16 13:12:21 +0000181 if sys.platform == 'darwin':
182 # for framework builds *only* we add the standard Apple
183 # locations. Currently only per-user, but /Library and
184 # /Network/Library could be added too
185 if 'Python.framework' in prefix:
Jack Jansen470b0c02003-06-03 10:55:35 +0000186 home = os.environ.get('HOME')
Jack Jansenbe5d7072003-04-16 13:12:21 +0000187 if home:
188 sitedirs.append(
189 os.path.join(home,
190 'Library',
191 'Python',
192 sys.version[:3],
193 'site-packages'))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000194 for sitedir in sitedirs:
195 if os.path.isdir(sitedir):
196 addsitedir(sitedir)
Neal Norwitz34172d52002-02-11 18:34:41 +0000197del prefix, sitedir
Guido van Rossume57c96e1996-08-17 19:56:26 +0000198
Fred Drake7f5296e2001-07-20 20:06:17 +0000199_dirs_in_sys_path = None
200
Fred Drake1fb5ce02001-07-02 16:55:42 +0000201
Guido van Rossumd89fa0c1998-08-07 18:01:14 +0000202# Define new built-ins 'quit' and 'exit'.
203# These are simply strings that display a hint on how to exit.
204if os.sep == ':':
205 exit = 'Use Cmd-Q to quit.'
206elif os.sep == '\\':
207 exit = 'Use Ctrl-Z plus Return to exit.'
208else:
209 exit = 'Use Ctrl-D (i.e. EOF) to exit.'
210import __builtin__
211__builtin__.quit = __builtin__.exit = exit
212del exit
213
Guido van Rossumd1252392000-09-05 04:39:55 +0000214# interactive prompt objects for printing the license text, a list of
215# contributors and the copyright notice.
216class _Printer:
217 MAXLINES = 23
218
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000219 def __init__(self, name, data, files=(), dirs=()):
220 self.__name = name
221 self.__data = data
222 self.__files = files
223 self.__dirs = dirs
224 self.__lines = None
225
226 def __setup(self):
227 if self.__lines:
228 return
229 data = None
230 for dir in self.__dirs:
231 for file in self.__files:
232 file = os.path.join(dir, file)
233 try:
234 fp = open(file)
235 data = fp.read()
236 fp.close()
237 break
238 except IOError:
239 pass
240 if data:
241 break
242 if not data:
243 data = self.__data
244 self.__lines = data.split('\n')
Guido van Rossumd1252392000-09-05 04:39:55 +0000245 self.__linecnt = len(self.__lines)
246
247 def __repr__(self):
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000248 self.__setup()
249 if len(self.__lines) <= self.MAXLINES:
250 return "\n".join(self.__lines)
251 else:
252 return "Type %s() to see the full %s text" % ((self.__name,)*2)
253
254 def __call__(self):
255 self.__setup()
Guido van Rossumd1252392000-09-05 04:39:55 +0000256 prompt = 'Hit Return for more, or q (and Return) to quit: '
257 lineno = 0
258 while 1:
259 try:
260 for i in range(lineno, lineno + self.MAXLINES):
261 print self.__lines[i]
262 except IndexError:
263 break
264 else:
265 lineno += self.MAXLINES
266 key = None
267 while key is None:
268 key = raw_input(prompt)
269 if key not in ('', 'q'):
270 key = None
271 if key == 'q':
272 break
Guido van Rossumd1252392000-09-05 04:39:55 +0000273
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000274__builtin__.copyright = _Printer("copyright", sys.copyright)
Barry Warsaw23f26ce2000-12-06 22:20:07 +0000275if sys.platform[:4] == 'java':
276 __builtin__.credits = _Printer(
277 "credits",
278 "Jython is maintained by the Jython developers (www.jython.org).")
279else:
280 __builtin__.credits = _Printer("credits", """\
Guido van Rossum2e1c09c2002-04-04 17:52:50 +0000281Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
Barry Warsaw23f26ce2000-12-06 22:20:07 +0000282for supporting Python development. See www.python.org for more information.""")
Guido van Rossumd1252392000-09-05 04:39:55 +0000283here = os.path.dirname(os.__file__)
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000284__builtin__.license = _Printer(
Guido van Rossume37e96d2001-10-02 18:27:09 +0000285 "license", "See http://www.python.org/%.3s/license.html" % sys.version,
Guido van Rossumf19a7ac2000-10-03 17:11:37 +0000286 ["LICENSE.txt", "LICENSE"],
Barry Warsaw62d24882001-03-23 17:53:49 +0000287 [os.path.join(here, os.pardir), here, os.curdir])
Guido van Rossumd1252392000-09-05 04:39:55 +0000288
289
Guido van Rossum83213cc2001-06-12 16:48:52 +0000290# Define new built-in 'help'.
291# This is a wrapper around pydoc.help (with a twist).
292
293class _Helper:
294 def __repr__(self):
295 return "Type help() for interactive help, " \
296 "or help(object) for help about object."
297 def __call__(self, *args, **kwds):
298 import pydoc
299 return pydoc.help(*args, **kwds)
300
301__builtin__.help = _Helper()
302
303
Martin v. Löwis4eab4862003-03-03 09:34:01 +0000304# On Windows, some default encodings are not provided
305# by Python (e.g. "cp932" in Japanese locale), while they
306# are always available as "mbcs" in each locale.
307# Make them usable by aliasing to "mbcs" in such a case.
308
309if sys.platform == 'win32':
310 import locale, codecs
311 enc = locale.getdefaultlocale()[1]
312 if enc.startswith('cp'): # "cp***" ?
313 try:
314 codecs.lookup(enc)
315 except LookupError:
316 import encodings
317 encodings._cache[enc] = encodings._unknown
318 encodings.aliases.aliases[enc] = 'mbcs'
319
Fredrik Lundh3fded4b2000-07-15 20:58:44 +0000320# Set the string encoding used by the Unicode implementation. The
321# default is 'ascii', but if you're willing to experiment, you can
322# change this.
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000323
Marc-André Lemburg09cad082000-09-18 11:06:00 +0000324encoding = "ascii" # Default value set by _PyUnicode_Init()
Fredrik Lundh47ac1262000-07-15 20:45:23 +0000325
326if 0:
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000327 # Enable to support locale aware default string encodings.
Fredrik Lundh47ac1262000-07-15 20:45:23 +0000328 import locale
329 loc = locale.getdefaultlocale()
330 if loc[1]:
331 encoding = loc[1]
332
333if 0:
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000334 # Enable to switch off string to Unicode coercion and implicit
335 # Unicode to string conversion.
Fredrik Lundh47ac1262000-07-15 20:45:23 +0000336 encoding = "undefined"
337
Marc-André Lemburg09cad082000-09-18 11:06:00 +0000338if encoding != "ascii":
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000339 # On Non-Unicode builds this will raise an AttributeError...
340 sys.setdefaultencoding(encoding) # Needs Python Unicode build !
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000341
342#
343# Run custom site specific code, if available.
344#
Guido van Rossume57c96e1996-08-17 19:56:26 +0000345try:
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000346 import sitecustomize
Guido van Rossume57c96e1996-08-17 19:56:26 +0000347except ImportError:
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000348 pass
349
350#
351# Remove sys.setdefaultencoding() so that users cannot change the
Fred Drake38cb9f12000-09-28 16:52:36 +0000352# encoding after initialization. The test for presence is needed when
Barry Warsaw23f26ce2000-12-06 22:20:07 +0000353# this module is run as a script, because this code is executed twice.
Marc-André Lemburg990bbe92000-06-07 09:12:09 +0000354#
Fred Drake38cb9f12000-09-28 16:52:36 +0000355if hasattr(sys, "setdefaultencoding"):
356 del sys.setdefaultencoding
Guido van Rossumf30bec71997-08-29 22:30:45 +0000357
358def _test():
359 print "sys.path = ["
360 for dir in sys.path:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000361 print " %s," % `dir`
Guido van Rossumf30bec71997-08-29 22:30:45 +0000362 print "]"
363
364if __name__ == '__main__':
365 _test()