py-cvs-rel2_1 (Rev 1.2) merge
[python/dscho.git] / Lib / site.py
blob7848553122f3866ac79a6cba27f40df9e508d6f9
1 """Append module search paths for third-party packages to sys.path.
3 ****************************************************************
4 * This module is automatically imported during initialization. *
5 ****************************************************************
7 In earlier versions of Python (up to 1.5a3), scripts or modules that
8 needed to use site-specific modules would place ``import site''
9 somewhere near the top of their code. Because of the automatic
10 import, this is no longer necessary (but code that does it still
11 works).
13 This will append site-specific paths to to the module search path. On
14 Unix, it starts with sys.prefix and sys.exec_prefix (if different) and
15 appends lib/python<version>/site-packages as well as lib/site-python.
16 On other platforms (mainly Mac and Windows), it uses just sys.prefix
17 \(and sys.exec_prefix, if different, but this is unlikely). The
18 resulting directories, if they exist, are appended to sys.path, and
19 also inspected for path configuration files.
21 A path configuration file is a file whose name has the form
22 <package>.pth; its contents are additional directories (one per line)
23 to be added to sys.path. Non-existing directories (or
24 non-directories) are never added to sys.path; no directory is added to
25 sys.path more than once. Blank lines and lines beginning with
26 \code{#} are skipped. Lines starting with \code{import} are executed.
28 For example, suppose sys.prefix and sys.exec_prefix are set to
29 /usr/local and there is a directory /usr/local/lib/python1.5/site-packages
30 with three subdirectories, foo, bar and spam, and two path
31 configuration files, foo.pth and bar.pth. Assume foo.pth contains the
32 following:
34 # foo package configuration
35 foo
36 bar
37 bletch
39 and bar.pth contains:
41 # bar package configuration
42 bar
44 Then the following directories are added to sys.path, in this order:
46 /usr/local/lib/python1.5/site-packages/bar
47 /usr/local/lib/python1.5/site-packages/foo
49 Note that bletch is omitted because it doesn't exist; bar precedes foo
50 because bar.pth comes alphabetically before foo.pth; and spam is
51 omitted because it is not mentioned in either path configuration file.
53 After these path manipulations, an attempt is made to import a module
54 named sitecustomize, which can perform arbitrary additional
55 site-specific customizations. If this import fails with an
56 ImportError exception, it is silently ignored.
58 """
60 import sys, os
62 if os.sep==".":
63 endsep = "/"
64 else:
65 endsep = "."
68 def makepath(*paths):
69 dir = os.path.abspath(os.path.join(*paths))
70 return dir, os.path.normcase(dir)
72 for m in sys.modules.values():
73 if hasattr(m, "__file__") and m.__file__:
74 m.__file__ = os.path.abspath(m.__file__)
75 del m
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 dirs_in_sys_path = {}
81 for dir in sys.path:
82 # Filter out paths that don't exist, but leave in the empty string
83 # since it's a special case.
84 if dir and not os.path.isdir(dir):
85 continue
86 dir, dircase = makepath(dir)
87 if not dirs_in_sys_path.has_key(dircase):
88 L.append(dir)
89 dirs_in_sys_path[dircase] = 1
90 sys.path[:] = L
91 del dir, L
93 # Append ./build/lib.<platform> in case we're running in the build dir
94 # (especially for Guido :-)
95 if os.name == "posix" and os.path.basename(sys.path[-1]) == "Modules":
96 from distutils.util import get_platform
97 s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
98 s = os.path.join(os.path.dirname(sys.path[-1]), s)
99 sys.path.append(s)
100 del get_platform, s
102 def addsitedir(sitedir):
103 sitedir, sitedircase = makepath(sitedir)
104 if not dirs_in_sys_path.has_key(sitedircase):
105 sys.path.append(sitedir) # Add path component
106 try:
107 names = os.listdir(sitedir)
108 except os.error:
109 return
110 names.sort()
111 for name in names:
112 if name[-4:] == endsep + "pth":
113 addpackage(sitedir, name)
115 def addpackage(sitedir, name):
116 fullname = os.path.join(sitedir, name)
117 try:
118 f = open(fullname)
119 except IOError:
120 return
121 while 1:
122 dir = f.readline()
123 if not dir:
124 break
125 if dir[0] == '#':
126 continue
127 if dir.startswith("import"):
128 exec dir
129 continue
130 if dir[-1] == '\n':
131 dir = dir[:-1]
132 dir, dircase = makepath(sitedir, dir)
133 if not dirs_in_sys_path.has_key(dircase) and os.path.exists(dir):
134 sys.path.append(dir)
135 dirs_in_sys_path[dircase] = 1
137 prefixes = [sys.prefix]
138 if sys.exec_prefix != sys.prefix:
139 prefixes.append(sys.exec_prefix)
140 for prefix in prefixes:
141 if prefix:
142 if os.sep == '/':
143 sitedirs = [os.path.join(prefix,
144 "lib",
145 "python" + sys.version[:3],
146 "site-packages"),
147 os.path.join(prefix, "lib", "site-python")]
148 else:
149 sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
150 for sitedir in sitedirs:
151 if os.path.isdir(sitedir):
152 addsitedir(sitedir)
154 del dirs_in_sys_path
156 # Define new built-ins 'quit' and 'exit'.
157 # These are simply strings that display a hint on how to exit.
158 if os.sep == ':':
159 exit = 'Use Cmd-Q to quit.'
160 elif os.sep == '\\':
161 exit = 'Use Ctrl-Z plus Return to exit.'
162 else:
163 exit = 'Use Ctrl-D (i.e. EOF) to exit.'
164 import __builtin__
165 __builtin__.quit = __builtin__.exit = exit
166 del exit
168 # interactive prompt objects for printing the license text, a list of
169 # contributors and the copyright notice.
170 class _Printer:
171 MAXLINES = 23
173 def __init__(self, name, data, files=(), dirs=()):
174 self.__name = name
175 self.__data = data
176 self.__files = files
177 self.__dirs = dirs
178 self.__lines = None
180 def __setup(self):
181 if self.__lines:
182 return
183 data = None
184 for dir in self.__dirs:
185 for file in self.__files:
186 file = os.path.join(dir, file)
187 try:
188 fp = open(file)
189 data = fp.read()
190 fp.close()
191 break
192 except IOError:
193 pass
194 if data:
195 break
196 if not data:
197 data = self.__data
198 self.__lines = data.split('\n')
199 self.__linecnt = len(self.__lines)
201 def __repr__(self):
202 self.__setup()
203 if len(self.__lines) <= self.MAXLINES:
204 return "\n".join(self.__lines)
205 else:
206 return "Type %s() to see the full %s text" % ((self.__name,)*2)
208 def __call__(self):
209 self.__setup()
210 prompt = 'Hit Return for more, or q (and Return) to quit: '
211 lineno = 0
212 while 1:
213 try:
214 for i in range(lineno, lineno + self.MAXLINES):
215 print self.__lines[i]
216 except IndexError:
217 break
218 else:
219 lineno += self.MAXLINES
220 key = None
221 while key is None:
222 key = raw_input(prompt)
223 if key not in ('', 'q'):
224 key = None
225 if key == 'q':
226 break
228 __builtin__.copyright = _Printer("copyright", sys.copyright)
229 if sys.platform[:4] == 'java':
230 __builtin__.credits = _Printer(
231 "credits",
232 "Jython is maintained by the Jython developers (www.jython.org).")
233 else:
234 __builtin__.credits = _Printer("credits", """\
235 Thanks to CWI, CNRI, BeOpen.com, Digital Creations and a cast of thousands
236 for supporting Python development. See www.python.org for more information.""")
237 here = os.path.dirname(os.__file__)
238 __builtin__.license = _Printer(
239 "license", "See http://www.pythonlabs.com/products/python2.0/license.html",
240 ["LICENSE.txt", "LICENSE"],
241 [os.path.join(here, os.pardir), here, os.curdir])
244 # Define new built-in 'help'.
245 # This is a wrapper around pydoc.help (with a twist).
247 class _Helper:
248 def __repr__(self):
249 return "Type help() for interactive help, " \
250 "or help(object) for help about object."
251 def __call__(self, *args, **kwds):
252 import pydoc
253 return pydoc.help(*args, **kwds)
255 __builtin__.help = _Helper()
258 # Set the string encoding used by the Unicode implementation. The
259 # default is 'ascii', but if you're willing to experiment, you can
260 # change this.
262 encoding = "ascii" # Default value set by _PyUnicode_Init()
264 if 0:
265 # Enable to support locale aware default string encodings.
266 import locale
267 loc = locale.getdefaultlocale()
268 if loc[1]:
269 encoding = loc[1]
271 if 0:
272 # Enable to switch off string to Unicode coercion and implicit
273 # Unicode to string conversion.
274 encoding = "undefined"
276 if encoding != "ascii":
277 sys.setdefaultencoding(encoding)
280 # Run custom site specific code, if available.
282 try:
283 import sitecustomize
284 except ImportError:
285 pass
288 # Remove sys.setdefaultencoding() so that users cannot change the
289 # encoding after initialization. The test for presence is needed when
290 # this module is run as a script, because this code is executed twice.
292 if hasattr(sys, "setdefaultencoding"):
293 del sys.setdefaultencoding
295 def _test():
296 print "sys.path = ["
297 for dir in sys.path:
298 print " %s," % `dir`
299 print "]"
301 if __name__ == '__main__':
302 _test()