This commit was manufactured by cvs2svn to create tag 'r22a4-fork'.
[python/dscho.git] / Lib / site.py
blobdfe658aa327a150d8d497a7a9747af24a213b54f
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. We also need to special-case the Mac,
84 # as file names are allowed on sys.path there.
85 if sys.platform != 'mac':
86 if dir and not os.path.isdir(dir):
87 continue
88 else:
89 if dir and not os.path.exists(dir):
90 continue
91 dir, dircase = makepath(dir)
92 if not _dirs_in_sys_path.has_key(dircase):
93 L.append(dir)
94 _dirs_in_sys_path[dircase] = 1
95 sys.path[:] = L
96 del dir, L
98 # Append ./build/lib.<platform> in case we're running in the build dir
99 # (especially for Guido :-)
100 if os.name == "posix" and os.path.basename(sys.path[-1]) == "Modules":
101 from distutils.util import get_platform
102 s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
103 s = os.path.join(os.path.dirname(sys.path[-1]), s)
104 sys.path.append(s)
105 del get_platform, s
107 def _init_pathinfo():
108 global _dirs_in_sys_path
109 _dirs_in_sys_path = d = {}
110 for dir in sys.path:
111 if dir and not os.path.isdir(dir):
112 continue
113 dir, dircase = makepath(dir)
114 d[dircase] = 1
116 def addsitedir(sitedir):
117 global _dirs_in_sys_path
118 if _dirs_in_sys_path is None:
119 _init_pathinfo()
120 reset = 1
121 else:
122 reset = 0
123 sitedir, sitedircase = makepath(sitedir)
124 if not _dirs_in_sys_path.has_key(sitedircase):
125 sys.path.append(sitedir) # Add path component
126 try:
127 names = os.listdir(sitedir)
128 except os.error:
129 return
130 names.sort()
131 for name in names:
132 if name[-4:] == endsep + "pth":
133 addpackage(sitedir, name)
134 if reset:
135 _dirs_in_sys_path = None
137 def addpackage(sitedir, name):
138 global _dirs_in_sys_path
139 if _dirs_in_sys_path is None:
140 _init_pathinfo()
141 reset = 1
142 else:
143 reset = 0
144 fullname = os.path.join(sitedir, name)
145 try:
146 f = open(fullname)
147 except IOError:
148 return
149 while 1:
150 dir = f.readline()
151 if not dir:
152 break
153 if dir[0] == '#':
154 continue
155 if dir.startswith("import"):
156 exec dir
157 continue
158 if dir[-1] == '\n':
159 dir = dir[:-1]
160 dir, dircase = makepath(sitedir, dir)
161 if not _dirs_in_sys_path.has_key(dircase) and os.path.exists(dir):
162 sys.path.append(dir)
163 _dirs_in_sys_path[dircase] = 1
164 if reset:
165 _dirs_in_sys_path = None
167 prefixes = [sys.prefix]
168 if sys.exec_prefix != sys.prefix:
169 prefixes.append(sys.exec_prefix)
170 for prefix in prefixes:
171 if prefix:
172 if os.sep == '/':
173 sitedirs = [os.path.join(prefix,
174 "lib",
175 "python" + sys.version[:3],
176 "site-packages"),
177 os.path.join(prefix, "lib", "site-python")]
178 else:
179 sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
180 for sitedir in sitedirs:
181 if os.path.isdir(sitedir):
182 addsitedir(sitedir)
184 _dirs_in_sys_path = None
187 # Define new built-ins 'quit' and 'exit'.
188 # These are simply strings that display a hint on how to exit.
189 if os.sep == ':':
190 exit = 'Use Cmd-Q to quit.'
191 elif os.sep == '\\':
192 exit = 'Use Ctrl-Z plus Return to exit.'
193 else:
194 exit = 'Use Ctrl-D (i.e. EOF) to exit.'
195 import __builtin__
196 __builtin__.quit = __builtin__.exit = exit
197 del exit
199 # interactive prompt objects for printing the license text, a list of
200 # contributors and the copyright notice.
201 class _Printer:
202 MAXLINES = 23
204 def __init__(self, name, data, files=(), dirs=()):
205 self.__name = name
206 self.__data = data
207 self.__files = files
208 self.__dirs = dirs
209 self.__lines = None
211 def __setup(self):
212 if self.__lines:
213 return
214 data = None
215 for dir in self.__dirs:
216 for file in self.__files:
217 file = os.path.join(dir, file)
218 try:
219 fp = open(file)
220 data = fp.read()
221 fp.close()
222 break
223 except IOError:
224 pass
225 if data:
226 break
227 if not data:
228 data = self.__data
229 self.__lines = data.split('\n')
230 self.__linecnt = len(self.__lines)
232 def __repr__(self):
233 self.__setup()
234 if len(self.__lines) <= self.MAXLINES:
235 return "\n".join(self.__lines)
236 else:
237 return "Type %s() to see the full %s text" % ((self.__name,)*2)
239 def __call__(self):
240 self.__setup()
241 prompt = 'Hit Return for more, or q (and Return) to quit: '
242 lineno = 0
243 while 1:
244 try:
245 for i in range(lineno, lineno + self.MAXLINES):
246 print self.__lines[i]
247 except IndexError:
248 break
249 else:
250 lineno += self.MAXLINES
251 key = None
252 while key is None:
253 key = raw_input(prompt)
254 if key not in ('', 'q'):
255 key = None
256 if key == 'q':
257 break
259 __builtin__.copyright = _Printer("copyright", sys.copyright)
260 if sys.platform[:4] == 'java':
261 __builtin__.credits = _Printer(
262 "credits",
263 "Jython is maintained by the Jython developers (www.jython.org).")
264 else:
265 __builtin__.credits = _Printer("credits", """\
266 Thanks to CWI, CNRI, BeOpen.com, Digital Creations and a cast of thousands
267 for supporting Python development. See www.python.org for more information.""")
268 here = os.path.dirname(os.__file__)
269 __builtin__.license = _Printer(
270 "license", "See http://www.pythonlabs.com/products/python2.0/license.html",
271 ["LICENSE.txt", "LICENSE"],
272 [os.path.join(here, os.pardir), here, os.curdir])
275 # Define new built-in 'help'.
276 # This is a wrapper around pydoc.help (with a twist).
278 class _Helper:
279 def __repr__(self):
280 return "Type help() for interactive help, " \
281 "or help(object) for help about object."
282 def __call__(self, *args, **kwds):
283 import pydoc
284 return pydoc.help(*args, **kwds)
286 __builtin__.help = _Helper()
289 # Set the string encoding used by the Unicode implementation. The
290 # default is 'ascii', but if you're willing to experiment, you can
291 # change this.
293 encoding = "ascii" # Default value set by _PyUnicode_Init()
295 if 0:
296 # Enable to support locale aware default string encodings.
297 import locale
298 loc = locale.getdefaultlocale()
299 if loc[1]:
300 encoding = loc[1]
302 if 0:
303 # Enable to switch off string to Unicode coercion and implicit
304 # Unicode to string conversion.
305 encoding = "undefined"
307 if encoding != "ascii":
308 # On Non-Unicode builds this will raise an AttributeError...
309 sys.setdefaultencoding(encoding) # Needs Python Unicode build !
312 # Run custom site specific code, if available.
314 try:
315 import sitecustomize
316 except ImportError:
317 pass
320 # Remove sys.setdefaultencoding() so that users cannot change the
321 # encoding after initialization. The test for presence is needed when
322 # this module is run as a script, because this code is executed twice.
324 if hasattr(sys, "setdefaultencoding"):
325 del sys.setdefaultencoding
327 def _test():
328 print "sys.path = ["
329 for dir in sys.path:
330 print " %s," % `dir`
331 print "]"
333 if __name__ == '__main__':
334 _test()