home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / SITE.PY < prev    next >
Encoding:
Python Source  |  2000-10-03  |  8.0 KB  |  258 lines

  1. """Append module search paths for third-party packages to sys.path.
  2.  
  3. ****************************************************************
  4. * This module is automatically imported during initialization. *
  5. ****************************************************************
  6.  
  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).
  12.  
  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.
  20.  
  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.
  27.  
  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:
  33.  
  34.   # foo package configuration
  35.   foo
  36.   bar
  37.   bletch
  38.  
  39. and bar.pth contains:
  40.  
  41.   # bar package configuration
  42.   bar
  43.  
  44. Then the following directories are added to sys.path, in this order:
  45.  
  46.   /usr/local/lib/python1.5/site-packages/bar
  47.   /usr/local/lib/python1.5/site-packages/foo
  48.  
  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.
  52.  
  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.
  57.  
  58. """
  59.  
  60. import sys, os
  61.  
  62. def makepath(*paths):
  63.     dir = os.path.join(*paths)
  64.     return os.path.normcase(os.path.abspath(dir))
  65.  
  66. L = sys.modules.values()
  67. for m in L:
  68.     if hasattr(m, "__file__"):
  69.         m.__file__ = makepath(m.__file__)
  70. del m, L
  71.  
  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.
  74. L = []
  75. for dir in sys.path:
  76.     dir = makepath(dir)
  77.     if dir not in L:
  78.         L.append(dir)
  79. sys.path[:] = L
  80. del dir, L
  81.  
  82. def addsitedir(sitedir):
  83.     sitedir = makepath(sitedir)
  84.     if sitedir not in sys.path:
  85.         sys.path.append(sitedir)        # Add path component
  86.     try:
  87.         names = os.listdir(sitedir)
  88.     except os.error:
  89.         return
  90.     names = map(os.path.normcase, names)
  91.     names.sort()
  92.     for name in names:
  93.         if name[-4:] == ".pth":
  94.             addpackage(sitedir, name)
  95.  
  96. def addpackage(sitedir, name):
  97.     fullname = os.path.join(sitedir, name)
  98.     try:
  99.         f = open(fullname)
  100.     except IOError:
  101.         return
  102.     while 1:
  103.         dir = f.readline()
  104.         if not dir:
  105.             break
  106.         if dir[0] == '#':
  107.             continue
  108.         if dir[-1] == '\n':
  109.             dir = dir[:-1]
  110.         dir = makepath(sitedir, dir)
  111.         if dir not in sys.path and os.path.exists(dir):
  112.             sys.path.append(dir)
  113.  
  114. prefixes = [sys.prefix]
  115. if sys.exec_prefix != sys.prefix:
  116.     prefixes.append(sys.exec_prefix)
  117. for prefix in prefixes:
  118.     if prefix:
  119.         if os.sep == '/':
  120.             sitedirs = [makepath(prefix,
  121.                                  "lib",
  122.                                  "python" + sys.version[:3],
  123.                                  "site-packages"),
  124.                         makepath(prefix, "lib", "site-python")]
  125.         else:
  126.             sitedirs = [prefix]
  127.         for sitedir in sitedirs:
  128.             if os.path.isdir(sitedir):
  129.                 addsitedir(sitedir)
  130.  
  131. # Define new built-ins 'quit' and 'exit'.
  132. # These are simply strings that display a hint on how to exit.
  133. if os.sep == ':':
  134.     exit = 'Use Cmd-Q to quit.'
  135. elif os.sep == '\\':
  136.     exit = 'Use Ctrl-Z plus Return to exit.'
  137. else:
  138.     exit = 'Use Ctrl-D (i.e. EOF) to exit.'
  139. import __builtin__
  140. __builtin__.quit = __builtin__.exit = exit
  141. del exit
  142.  
  143. # interactive prompt objects for printing the license text, a list of
  144. # contributors and the copyright notice.
  145. class _Printer:
  146.     MAXLINES = 23
  147.  
  148.     def __init__(self, name, data, files=(), dirs=()):
  149.         self.__name = name
  150.         self.__data = data
  151.         self.__files = files
  152.         self.__dirs = dirs
  153.         self.__lines = None
  154.  
  155.     def __setup(self):
  156.         if self.__lines:
  157.             return
  158.         data = None
  159.         for dir in self.__dirs:
  160.             for file in self.__files:
  161.                 file = os.path.join(dir, file)
  162.                 try:
  163.                     fp = open(file)
  164.                     data = fp.read()
  165.                     fp.close()
  166.                     break
  167.                 except IOError:
  168.                     pass
  169.             if data:
  170.                 break
  171.         if not data:
  172.             data = self.__data
  173.         self.__lines = data.split('\n')
  174.         self.__linecnt = len(self.__lines)
  175.  
  176.     def __repr__(self):
  177.         self.__setup()
  178.         if len(self.__lines) <= self.MAXLINES:
  179.             return "\n".join(self.__lines)
  180.         else:
  181.             return "Type %s() to see the full %s text" % ((self.__name,)*2)
  182.  
  183.     def __call__(self):
  184.         self.__setup()
  185.         prompt = 'Hit Return for more, or q (and Return) to quit: '
  186.         lineno = 0
  187.         while 1:
  188.             try:
  189.                 for i in range(lineno, lineno + self.MAXLINES):
  190.                     print self.__lines[i]
  191.             except IndexError:
  192.                 break
  193.             else:
  194.                 lineno += self.MAXLINES
  195.                 key = None
  196.                 while key is None:
  197.                     key = raw_input(prompt)
  198.                     if key not in ('', 'q'):
  199.                         key = None
  200.                 if key == 'q':
  201.                     break
  202.  
  203. __builtin__.copyright = _Printer("copyright", sys.copyright)
  204. __builtin__.credits = _Printer("credits",
  205.     "Python development is led by BeOpen PythonLabs (www.pythonlabs.com).")
  206. here = os.path.dirname(os.__file__)
  207. __builtin__.license = _Printer(
  208.     "license", "See http://www.pythonlabs.com/products/python2.0/license.html",
  209.     ["LICENSE.txt", "LICENSE"],
  210.     [here, os.path.join(here, os.pardir), os.curdir])
  211.  
  212.  
  213. # Set the string encoding used by the Unicode implementation.  The
  214. # default is 'ascii', but if you're willing to experiment, you can
  215. # change this.
  216.  
  217. encoding = "ascii" # Default value set by _PyUnicode_Init()
  218.  
  219. if 0:
  220.     # Enable to support locale aware default string encodings.
  221.     import locale
  222.     loc = locale.getdefaultlocale()
  223.     if loc[1]:
  224.         encoding = loc[1]
  225.  
  226. if 0:
  227.     # Enable to switch off string to Unicode coercion and implicit
  228.     # Unicode to string conversion.
  229.     encoding = "undefined"
  230.  
  231. if encoding != "ascii":
  232.     sys.setdefaultencoding(encoding)
  233.  
  234. #
  235. # Run custom site specific code, if available.
  236. #
  237. try:
  238.     import sitecustomize
  239. except ImportError:
  240.     pass
  241.  
  242. #
  243. # Remove sys.setdefaultencoding() so that users cannot change the
  244. # encoding after initialization.  The test for presence is needed when
  245. # this module is run as a script, becuase this code is executed twice.
  246. #
  247. if hasattr(sys, "setdefaultencoding"):
  248.     del sys.setdefaultencoding
  249.  
  250. def _test():
  251.     print "sys.path = ["
  252.     for dir in sys.path:
  253.         print "    %s," % `dir`
  254.     print "]"
  255.  
  256. if __name__ == '__main__':
  257.     _test()
  258.