This commit was manufactured by cvs2svn to create tag 'r211c1'.
[python/dscho.git] / Lib / site.py
blob5ad570e2792b33b13e8324777966b0eb52491e64
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 dir, dircase = makepath(dir)
83 if not dirs_in_sys_path.has_key(dircase):
84 L.append(dir)
85 dirs_in_sys_path[dircase] = 1
86 sys.path[:] = L
87 del dir, L
89 # Append ./build/lib.<platform> in case we're running in the build dir
90 # (especially for Guido :-)
91 if os.name == "posix" and os.path.basename(sys.path[-1]) == "Modules":
92 from distutils.util import get_platform
93 s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
94 s = os.path.join(os.path.dirname(sys.path[-1]), s)
95 sys.path.append(s)
96 del get_platform, s
98 def addsitedir(sitedir):
99 sitedir, sitedircase = makepath(sitedir)
100 if not dirs_in_sys_path.has_key(sitedircase):
101 sys.path.append(sitedir) # Add path component
102 try:
103 names = os.listdir(sitedir)
104 except os.error:
105 return
106 names.sort()
107 for name in names:
108 if name[-4:] == endsep + "pth":
109 addpackage(sitedir, name)
111 def addpackage(sitedir, name):
112 fullname = os.path.join(sitedir, name)
113 try:
114 f = open(fullname)
115 except IOError:
116 return
117 while 1:
118 dir = f.readline()
119 if not dir:
120 break
121 if dir[0] == '#':
122 continue
123 if dir.startswith("import"):
124 exec dir
125 continue
126 if dir[-1] == '\n':
127 dir = dir[:-1]
128 dir, dircase = makepath(sitedir, dir)
129 if not dirs_in_sys_path.has_key(dircase) and os.path.exists(dir):
130 sys.path.append(dir)
131 dirs_in_sys_path[dircase] = 1
133 prefixes = [sys.prefix]
134 if sys.exec_prefix != sys.prefix:
135 prefixes.append(sys.exec_prefix)
136 for prefix in prefixes:
137 if prefix:
138 if os.sep == '/':
139 sitedirs = [os.path.join(prefix,
140 "lib",
141 "python" + sys.version[:3],
142 "site-packages"),
143 os.path.join(prefix, "lib", "site-python")]
144 elif os.sep == ':':
145 sitedirs = [os.path.join(prefix, "lib", "site-packages")]
146 else:
147 sitedirs = [prefix]
148 for sitedir in sitedirs:
149 if os.path.isdir(sitedir):
150 addsitedir(sitedir)
152 del dirs_in_sys_path
154 # Define new built-ins 'quit' and 'exit'.
155 # These are simply strings that display a hint on how to exit.
156 if os.sep == ':':
157 exit = 'Use Cmd-Q to quit.'
158 elif os.sep == '\\':
159 exit = 'Use Ctrl-Z plus Return to exit.'
160 else:
161 exit = 'Use Ctrl-D (i.e. EOF) to exit.'
162 import __builtin__
163 __builtin__.quit = __builtin__.exit = exit
164 del exit
166 # interactive prompt objects for printing the license text, a list of
167 # contributors and the copyright notice.
168 class _Printer:
169 MAXLINES = 23
171 def __init__(self, name, data, files=(), dirs=()):
172 self.__name = name
173 self.__data = data
174 self.__files = files
175 self.__dirs = dirs
176 self.__lines = None
178 def __setup(self):
179 if self.__lines:
180 return
181 data = None
182 for dir in self.__dirs:
183 for file in self.__files:
184 file = os.path.join(dir, file)
185 try:
186 fp = open(file)
187 data = fp.read()
188 fp.close()
189 break
190 except IOError:
191 pass
192 if data:
193 break
194 if not data:
195 data = self.__data
196 self.__lines = data.split('\n')
197 self.__linecnt = len(self.__lines)
199 def __repr__(self):
200 self.__setup()
201 if len(self.__lines) <= self.MAXLINES:
202 return "\n".join(self.__lines)
203 else:
204 return "Type %s() to see the full %s text" % ((self.__name,)*2)
206 def __call__(self):
207 self.__setup()
208 prompt = 'Hit Return for more, or q (and Return) to quit: '
209 lineno = 0
210 while 1:
211 try:
212 for i in range(lineno, lineno + self.MAXLINES):
213 print self.__lines[i]
214 except IndexError:
215 break
216 else:
217 lineno += self.MAXLINES
218 key = None
219 while key is None:
220 key = raw_input(prompt)
221 if key not in ('', 'q'):
222 key = None
223 if key == 'q':
224 break
226 __builtin__.copyright = _Printer("copyright", sys.copyright)
227 if sys.platform[:4] == 'java':
228 __builtin__.credits = _Printer(
229 "credits",
230 "Jython is maintained by the Jython developers (www.jython.org).")
231 else:
232 __builtin__.credits = _Printer("credits", """\
233 Thanks to CWI, CNRI, BeOpen.com, Digital Creations and a cast of thousands
234 for supporting Python development. See www.python.org for more information.""")
235 here = os.path.dirname(os.__file__)
236 __builtin__.license = _Printer(
237 "license", "See http://www.pythonlabs.com/products/python2.0/license.html",
238 ["LICENSE.txt", "LICENSE"],
239 [os.path.join(here, os.pardir), here, os.curdir])
242 # Set the string encoding used by the Unicode implementation. The
243 # default is 'ascii', but if you're willing to experiment, you can
244 # change this.
246 encoding = "ascii" # Default value set by _PyUnicode_Init()
248 if 0:
249 # Enable to support locale aware default string encodings.
250 import locale
251 loc = locale.getdefaultlocale()
252 if loc[1]:
253 encoding = loc[1]
255 if 0:
256 # Enable to switch off string to Unicode coercion and implicit
257 # Unicode to string conversion.
258 encoding = "undefined"
260 if encoding != "ascii":
261 sys.setdefaultencoding(encoding)
264 # Run custom site specific code, if available.
266 try:
267 import sitecustomize
268 except ImportError:
269 pass
272 # Remove sys.setdefaultencoding() so that users cannot change the
273 # encoding after initialization. The test for presence is needed when
274 # this module is run as a script, because this code is executed twice.
276 if hasattr(sys, "setdefaultencoding"):
277 del sys.setdefaultencoding
279 def _test():
280 print "sys.path = ["
281 for dir in sys.path:
282 print " %s," % `dir`
283 print "]"
285 if __name__ == '__main__':
286 _test()