home *** CD-ROM | disk | FTP | other *** search
/ PC World 2002 May / PCWorld_2002-05_cd.bin / Software / TemaCD / activepython / ActivePython-2.1.1.msi / Python21_Lib_site.py < prev    next >
Encoding:
Python Source  |  2001-07-26  |  9.5 KB  |  301 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. Lines starting with \code{import} are executed.
  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. if os.sep==".":
  63.     endsep = "/"
  64. else:
  65.     endsep = "."
  66.  
  67.  
  68. def makepath(*paths):
  69.     dir = os.path.abspath(os.path.join(*paths))
  70.     return dir, os.path.normcase(dir)
  71.  
  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
  76.  
  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
  88.  
  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
  97.  
  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)
  110.  
  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
  132.  
  133.  
  134. prefixes = [sys.prefix]
  135. if sys.exec_prefix != sys.prefix:
  136.     prefixes.append(sys.exec_prefix)
  137. for prefix in prefixes:
  138.     if prefix:
  139.         if os.sep == '/':
  140.             sitedirs = [os.path.join(prefix,
  141.                                      "lib",
  142.                                      "python" + sys.version[:3],
  143.                                      "site-packages"),
  144.                         os.path.join(prefix, "lib", "site-python")]
  145.         elif os.sep == ':':
  146.             sitedirs = [os.path.join(prefix, "lib", "site-packages")]
  147.         else:
  148.             sitedirs = [prefix]
  149.         for sitedir in sitedirs:
  150.             if os.path.isdir(sitedir):
  151.                 addsitedir(sitedir)
  152.  
  153. # Define new built-ins 'quit' and 'exit'.
  154. # These are simply strings that display a hint on how to exit.
  155. if os.sep == ':':
  156.     exit = 'Use Cmd-Q to quit.'
  157. elif os.sep == '\\':
  158.     exit = 'Use Ctrl-Z plus Return to exit.'
  159. else:
  160.     exit = 'Use Ctrl-D (i.e. EOF) to exit.'
  161. import __builtin__
  162. __builtin__.quit = __builtin__.exit = exit
  163. del exit
  164.  
  165. # interactive prompt objects for printing the license text, a list of
  166. # contributors and the copyright notice.
  167. class _Printer:
  168.     MAXLINES = 23
  169.  
  170.     def __init__(self, name, data, files=(), dirs=()):
  171.         self.__name = name
  172.         self.__data = data
  173.         self.__files = files
  174.         self.__dirs = dirs
  175.         self.__lines = None
  176.  
  177.     def __setup(self):
  178.         if self.__lines:
  179.             return
  180.         data = None
  181.         for dir in self.__dirs:
  182.             for file in self.__files:
  183.                 file = os.path.join(dir, file)
  184.                 try:
  185.                     fp = open(file)
  186.                     data = fp.read()
  187.                     fp.close()
  188.                     break
  189.                 except IOError:
  190.                     pass
  191.             if data:
  192.                 break
  193.         if not data:
  194.             data = self.__data
  195.         self.__lines = data.split('\n')
  196.         self.__linecnt = len(self.__lines)
  197.  
  198.     def __repr__(self):
  199.         self.__setup()
  200.         if len(self.__lines) <= self.MAXLINES:
  201.             return "\n".join(self.__lines)
  202.         else:
  203.             return "Type %s() to see the full %s text" % ((self.__name,)*2)
  204.  
  205.     def __call__(self):
  206.         self.__setup()
  207.         prompt = 'Hit Return for more, or q (and Return) to quit: '
  208.         lineno = 0
  209.         while 1:
  210.             try:
  211.                 for i in range(lineno, lineno + self.MAXLINES):
  212.                     print self.__lines[i]
  213.             except IndexError:
  214.                 break
  215.             else:
  216.                 lineno += self.MAXLINES
  217.                 key = None
  218.                 while key is None:
  219.                     key = raw_input(prompt)
  220.                     if key not in ('', 'q'):
  221.                         key = None
  222.                 if key == 'q':
  223.                     break
  224.  
  225. __builtin__.copyright = _Printer("copyright", sys.copyright)
  226. if sys.platform[:4] == 'java':
  227.     __builtin__.credits = _Printer(
  228.         "credits",
  229.         "Jython is maintained by the Jython developers (www.jython.org).")
  230. else:
  231.     __builtin__.credits = _Printer("credits", """\
  232. ActivePython is a Python distribution by ActiveState Tool Corp.
  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", 
  238.  "See http://www.activestate.com/Products/ActivePython/License_Agreement.html",
  239.     ["LICENSE.txt", "LICENSE"],
  240.     [os.path.join(here, os.pardir), here, os.curdir])
  241.  
  242.  
  243. class Helper:
  244.         def __repr__(self):
  245.             import inspect
  246.             if inspect.stack()[1][3] == '?':
  247.                 self()
  248.                 return ''
  249.             return '<Helper instance>'
  250.         def __call__(self, arg=None):
  251.             import pydoc
  252.             pydoc.help(arg)
  253.  
  254. __builtin__.help = Helper()
  255.  
  256. # Set the string encoding used by the Unicode implementation.  The
  257. # default is 'ascii', but if you're willing to experiment, you can
  258. # change this.
  259.  
  260. encoding = "ascii" # Default value set by _PyUnicode_Init()
  261.  
  262. if 0:
  263.     # Enable to support locale aware default string encodings.
  264.     import locale
  265.     loc = locale.getdefaultlocale()
  266.     if loc[1]:
  267.         encoding = loc[1]
  268.  
  269. if 0:
  270.     # Enable to switch off string to Unicode coercion and implicit
  271.     # Unicode to string conversion.
  272.     encoding = "undefined"
  273.  
  274. if encoding != "ascii":
  275.     sys.setdefaultencoding(encoding)
  276.  
  277. #
  278. # Run custom site specific code, if available.
  279. #
  280. try:
  281.     import sitecustomize
  282. except ImportError:
  283.     pass
  284.  
  285. #
  286. # Remove sys.setdefaultencoding() so that users cannot change the
  287. # encoding after initialization.  The test for presence is needed when
  288. # this module is run as a script, because this code is executed twice.
  289. #
  290. if hasattr(sys, "setdefaultencoding"):
  291.     del sys.setdefaultencoding
  292.  
  293. def _test():
  294.     print "sys.path = ["
  295.     for dir in sys.path:
  296.         print "    %s," % `dir`
  297.     print "]"
  298.  
  299. if __name__ == '__main__':
  300.     _test()
  301.