0001 """Append module search paths for third-party packages to sys.path. 0002 0003 **************************************************************** 0004 * This module is automatically imported during initialization. * 0005 **************************************************************** 0006 0007 In earlier versions of Python (up to 1.5a3), scripts or modules that 0008 needed to use site-specific modules would place ``import site'' 0009 somewhere near the top of their code. Because of the automatic 0010 import, this is no longer necessary (but code that does it still 0011 works). 0012 0013 This will append site-specific paths to the module search path. On 0014 Unix, it starts with sys.prefix and sys.exec_prefix (if different) and 0015 appends lib/python<version>/site-packages as well as lib/site-python. 0016 On other platforms (mainly Mac and Windows), it uses just sys.prefix 0017 (and sys.exec_prefix, if different, but this is unlikely). The 0018 resulting directories, if they exist, are appended to sys.path, and 0019 also inspected for path configuration files. 0020 0021 A path configuration file is a file whose name has the form 0022 <package>.pth; its contents are additional directories (one per line) 0023 to be added to sys.path. Non-existing directories (or 0024 non-directories) are never added to sys.path; no directory is added to 0025 sys.path more than once. Blank lines and lines beginning with 0026 '#' are skipped. Lines starting with 'import' are executed. 0027 0028 For example, suppose sys.prefix and sys.exec_prefix are set to 0029 /usr/local and there is a directory /usr/local/lib/python1.5/site-packages 0030 with three subdirectories, foo, bar and spam, and two path 0031 configuration files, foo.pth and bar.pth. Assume foo.pth contains the 0032 following: 0033 0034 # foo package configuration 0035 foo 0036 bar 0037 bletch 0038 0039 and bar.pth contains: 0040 0041 # bar package configuration 0042 bar 0043 0044 Then the following directories are added to sys.path, in this order: 0045 0046 /usr/local/lib/python1.5/site-packages/bar 0047 /usr/local/lib/python1.5/site-packages/foo 0048 0049 Note that bletch is omitted because it doesn't exist; bar precedes foo 0050 because bar.pth comes alphabetically before foo.pth; and spam is 0051 omitted because it is not mentioned in either path configuration file. 0052 0053 After these path manipulations, an attempt is made to import a module 0054 named sitecustomize, which can perform arbitrary additional 0055 site-specific customizations. If this import fails with an 0056 ImportError exception, it is silently ignored. 0057 0058 """ 0059 0060 import sys 0061 import os 0062 import __builtin__ 0063 0064 0065 def makepath(*paths): 0066 dir = os.path.abspath(os.path.join(*paths)) 0067 return dir, os.path.normcase(dir) 0068 0069 def abs__file__(): 0070 """Set all module' __file__ attribute to an absolute path""" 0071 for m in sys.modules.values(): 0072 try: 0073 m.__file__ = os.path.abspath(m.__file__) 0074 except AttributeError: 0075 continue 0076 0077 def removeduppaths(): 0078 """ Remove duplicate entries from sys.path along with making them 0079 absolute""" 0080 # This ensures that the initial path provided by the interpreter contains 0081 # only absolute pathnames, even if we're running from the build directory. 0082 L = [] 0083 known_paths = set() 0084 for dir in sys.path: 0085 # Filter out duplicate paths (on case-insensitive file systems also 0086 # if they only differ in case); turn relative paths into absolute 0087 # paths. 0088 dir, dircase = makepath(dir) 0089 if not dircase in known_paths: 0090 L.append(dir) 0091 known_paths.add(dircase) 0092 sys.path[:] = L 0093 return known_paths 0094 0095 # XXX This should not be part of site.py, since it is needed even when 0096 # using the -S option for Python. See http://www.python.org/sf/586680 0097 def addbuilddir(): 0098 """Append ./build/lib.<platform> in case we're running in the build dir 0099 (especially for Guido :-)""" 0100 from distutils.util import get_platform 0101 s = "build/lib.%s-%.3s" % (get_platform(), sys.version) 0102 s = os.path.join(os.path.dirname(sys.path[-1]), s) 0103 sys.path.append(s) 0104 0105 def _init_pathinfo(): 0106 """Return a set containing all existing directory entries from sys.path""" 0107 d = set() 0108 for dir in sys.path: 0109 try: 0110 if os.path.isdir(dir): 0111 dir, dircase = makepath(dir) 0112 d.add(dircase) 0113 except TypeError: 0114 continue 0115 return d 0116 0117 def addpackage(sitedir, name, known_paths): 0118 """Add a new path to known_paths by combining sitedir and 'name' or execute 0119 sitedir if it starts with 'import'""" 0120 if known_paths is None: 0121 _init_pathinfo() 0122 reset = 1 0123 else: 0124 reset = 0 0125 fullname = os.path.join(sitedir, name) 0126 try: 0127 f = open(fullname, "rU") 0128 except IOError: 0129 return 0130 try: 0131 for line in f: 0132 if line.startswith("#"): 0133 continue 0134 if line.startswith("import"): 0135 exec line 0136 continue 0137 line = line.rstrip() 0138 dir, dircase = makepath(sitedir, line) 0139 if not dircase in known_paths and os.path.exists(dir): 0140 sys.path.append(dir) 0141 known_paths.add(dircase) 0142 finally: 0143 f.close() 0144 if reset: 0145 known_paths = None 0146 return known_paths 0147 0148 def addsitedir(sitedir, known_paths=None): 0149 """Add 'sitedir' argument to sys.path if missing and handle .pth files in 0150 'sitedir'""" 0151 if known_paths is None: 0152 known_paths = _init_pathinfo() 0153 reset = 1 0154 else: 0155 reset = 0 0156 sitedir, sitedircase = makepath(sitedir) 0157 if not sitedircase in known_paths: 0158 sys.path.append(sitedir) # Add path component 0159 try: 0160 names = os.listdir(sitedir) 0161 except os.error: 0162 return 0163 names.sort() 0164 for name in names: 0165 if name.endswith(os.extsep + "pth"): 0166 addpackage(sitedir, name, known_paths) 0167 if reset: 0168 known_paths = None 0169 return known_paths 0170 0171 def addsitepackages(known_paths): 0172 """Add site-packages (and possibly site-python) to sys.path""" 0173 prefixes = [sys.prefix] 0174 if sys.exec_prefix != sys.prefix: 0175 prefixes.append(sys.exec_prefix) 0176 for prefix in prefixes: 0177 if prefix: 0178 if sys.platform in ('os2emx', 'riscos'): 0179 sitedirs = [os.path.join(prefix, "Lib", "site-packages")] 0180 elif os.sep == '/': 0181 sitedirs = [os.path.join(prefix, 0182 "lib", 0183 "python" + sys.version[:3], 0184 "site-packages"), 0185 os.path.join(prefix, "lib", "site-python")] 0186 else: 0187 sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")] 0188 if sys.platform == 'darwin': 0189 # for framework builds *only* we add the standard Apple 0190 # locations. Currently only per-user, but /Library and 0191 # /Network/Library could be added too 0192 if 'Python.framework' in prefix: 0193 home = os.environ.get('HOME') 0194 if home: 0195 sitedirs.append( 0196 os.path.join(home, 0197 'Library', 0198 'Python', 0199 sys.version[:3], 0200 'site-packages')) 0201 for sitedir in sitedirs: 0202 if os.path.isdir(sitedir): 0203 addsitedir(sitedir, known_paths) 0204 return None 0205 0206 0207 def setBEGINLIBPATH(): 0208 """The OS/2 EMX port has optional extension modules that do double duty 0209 as DLLs (and must use the .DLL file extension) for other extensions. 0210 The library search path needs to be amended so these will be found 0211 during module import. Use BEGINLIBPATH so that these are at the start 0212 of the library search path. 0213 0214 """ 0215 dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload") 0216 libpath = os.environ['BEGINLIBPATH'].split(';') 0217 if libpath[-1]: 0218 libpath.append(dllpath) 0219 else: 0220 libpath[-1] = dllpath 0221 os.environ['BEGINLIBPATH'] = ';'.join(libpath) 0222 0223 0224 def setquit(): 0225 """Define new built-ins 'quit' and 'exit'. 0226 These are simply strings that display a hint on how to exit. 0227 0228 """ 0229 if os.sep == ':': 0230 exit = 'Use Cmd-Q to quit.' 0231 elif os.sep == '\\': 0232 exit = 'Use Ctrl-Z plus Return to exit.' 0233 else: 0234 exit = 'Use Ctrl-D (i.e. EOF) to exit.' 0235 __builtin__.quit = __builtin__.exit = exit 0236 0237 0238 class _Printer(object): 0239 """interactive prompt objects for printing the license text, a list of 0240 contributors and the copyright notice.""" 0241 0242 MAXLINES = 23 0243 0244 def __init__(self, name, data, files=(), dirs=()): 0245 self.__name = name 0246 self.__data = data 0247 self.__files = files 0248 self.__dirs = dirs 0249 self.__lines = None 0250 0251 def __setup(self): 0252 if self.__lines: 0253 return 0254 data = None 0255 for dir in self.__dirs: 0256 for filename in self.__files: 0257 filename = os.path.join(dir, filename) 0258 try: 0259 fp = file(filename, "rU") 0260 data = fp.read() 0261 fp.close() 0262 break 0263 except IOError: 0264 pass 0265 if data: 0266 break 0267 if not data: 0268 data = self.__data 0269 self.__lines = data.split('\n') 0270 self.__linecnt = len(self.__lines) 0271 0272 def __repr__(self): 0273 self.__setup() 0274 if len(self.__lines) <= self.MAXLINES: 0275 return "\n".join(self.__lines) 0276 else: 0277 return "Type %s() to see the full %s text" % ((self.__name,)*2) 0278 0279 def __call__(self): 0280 self.__setup() 0281 prompt = 'Hit Return for more, or q (and Return) to quit: ' 0282 lineno = 0 0283 while 1: 0284 try: 0285 for i in range(lineno, lineno + self.MAXLINES): 0286 print self.__lines[i] 0287 except IndexError: 0288 break 0289 else: 0290 lineno += self.MAXLINES 0291 key = None 0292 while key is None: 0293 key = raw_input(prompt) 0294 if key not in ('', 'q'): 0295 key = None 0296 if key == 'q': 0297 break 0298 0299 def setcopyright(): 0300 """Set 'copyright' and 'credits' in __builtin__""" 0301 __builtin__.copyright = _Printer("copyright", sys.copyright) 0302 if sys.platform[:4] == 'java': 0303 __builtin__.credits = _Printer( 0304 "credits", 0305 "Jython is maintained by the Jython developers (www.jython.org).") 0306 else: 0307 __builtin__.credits = _Printer("credits", """\ 0308 Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands 0309 for supporting Python development. See www.python.org for more information.""") 0310 here = os.path.dirname(os.__file__) 0311 __builtin__.license = _Printer( 0312 "license", "See http://www.python.org/%.3s/license.html" % sys.version, 0313 ["LICENSE.txt", "LICENSE"], 0314 [os.path.join(here, os.pardir), here, os.curdir]) 0315 0316 0317 class _Helper(object): 0318 """Define the built-in 'help'. 0319 This is a wrapper around pydoc.help (with a twist). 0320 0321 """ 0322 0323 def __repr__(self): 0324 return "Type help() for interactive help, " \ 0325 "or help(object) for help about object." 0326 def __call__(self, *args, **kwds): 0327 import pydoc 0328 return pydoc.help(*args, **kwds) 0329 0330 def sethelper(): 0331 __builtin__.help = _Helper() 0332 0333 def aliasmbcs(): 0334 """On Windows, some default encodings are not provided by Python, 0335 while they are always available as "mbcs" in each locale. Make 0336 them usable by aliasing to "mbcs" in such a case.""" 0337 if sys.platform == 'win32': 0338 import locale, codecs 0339 enc = locale.getdefaultlocale()[1] 0340 if enc.startswith('cp'): # "cp***" ? 0341 try: 0342 codecs.lookup(enc) 0343 except LookupError: 0344 import encodings 0345 encodings._cache[enc] = encodings._unknown 0346 encodings.aliases.aliases[enc] = 'mbcs' 0347 0348 def setencoding(): 0349 """Set the string encoding used by the Unicode implementation. The 0350 default is 'ascii', but if you're willing to experiment, you can 0351 change this.""" 0352 encoding = "ascii" # Default value set by _PyUnicode_Init() 0353 if 0: 0354 # Enable to support locale aware default string encodings. 0355 import locale 0356 loc = locale.getdefaultlocale() 0357 if loc[1]: 0358 encoding = loc[1] 0359 if 0: 0360 # Enable to switch off string to Unicode coercion and implicit 0361 # Unicode to string conversion. 0362 encoding = "undefined" 0363 if encoding != "ascii": 0364 # On Non-Unicode builds this will raise an AttributeError... 0365 sys.setdefaultencoding(encoding) # Needs Python Unicode build ! 0366 0367 0368 def execsitecustomize(): 0369 """Run custom site specific code, if available.""" 0370 try: 0371 import sitecustomize 0372 except ImportError: 0373 pass 0374 0375 0376 def main(): 0377 abs__file__() 0378 paths_in_sys = removeduppaths() 0379 if (os.name == "posix" and sys.path and 0380 os.path.basename(sys.path[-1]) == "Modules"): 0381 addbuilddir() 0382 paths_in_sys = addsitepackages(paths_in_sys) 0383 if sys.platform == 'os2emx': 0384 setBEGINLIBPATH() 0385 setquit() 0386 setcopyright() 0387 sethelper() 0388 aliasmbcs() 0389 setencoding() 0390 execsitecustomize() 0391 # Remove sys.setdefaultencoding() so that users cannot change the 0392 # encoding after initialization. The test for presence is needed when 0393 # this module is run as a script, because this code is executed twice. 0394 if hasattr(sys, "setdefaultencoding"): 0395 del sys.setdefaultencoding 0396 0397 main() 0398 0399 def _test(): 0400 print "sys.path = [" 0401 for dir in sys.path: 0402 print " %r," % (dir,) 0403 print "]" 0404 0405 if __name__ == '__main__': 0406 _test() 0407
Generated by PyXR 0.9.4