site.py
上传用户:kylir999
上传日期:2019-09-03
资源大小:38451k
文件大小:19k
源码类别:

Windows编程

开发平台:

Perl

  1. """Append module search paths for third-party packages to sys.path.
  2. ****************************************************************
  3. * This module is automatically imported during initialization. *
  4. ****************************************************************
  5. In earlier versions of Python (up to 1.5a3), scripts or modules that
  6. needed to use site-specific modules would place ``import site''
  7. somewhere near the top of their code.  Because of the automatic
  8. import, this is no longer necessary (but code that does it still
  9. works).
  10. This will append site-specific paths to the module search path.  On
  11. Unix (including Mac OSX), it starts with sys.prefix and
  12. sys.exec_prefix (if different) and appends
  13. lib/python<version>/site-packages as well as lib/site-python.
  14. On other platforms (such as Windows), it tries each of the
  15. prefixes directly, as well as with lib/site-packages appended.  The
  16. resulting directories, if they exist, are appended to sys.path, and
  17. also inspected for path configuration files.
  18. A path configuration file is a file whose name has the form
  19. <package>.pth; its contents are additional directories (one per line)
  20. to be added to sys.path.  Non-existing directories (or
  21. non-directories) are never added to sys.path; no directory is added to
  22. sys.path more than once.  Blank lines and lines beginning with
  23. '#' are skipped. Lines starting with 'import' are executed.
  24. For example, suppose sys.prefix and sys.exec_prefix are set to
  25. /usr/local and there is a directory /usr/local/lib/python2.5/site-packages
  26. with three subdirectories, foo, bar and spam, and two path
  27. configuration files, foo.pth and bar.pth.  Assume foo.pth contains the
  28. following:
  29.   # foo package configuration
  30.   foo
  31.   bar
  32.   bletch
  33. and bar.pth contains:
  34.   # bar package configuration
  35.   bar
  36. Then the following directories are added to sys.path, in this order:
  37.   /usr/local/lib/python2.5/site-packages/bar
  38.   /usr/local/lib/python2.5/site-packages/foo
  39. Note that bletch is omitted because it doesn't exist; bar precedes foo
  40. because bar.pth comes alphabetically before foo.pth; and spam is
  41. omitted because it is not mentioned in either path configuration file.
  42. After these path manipulations, an attempt is made to import a module
  43. named sitecustomize, which can perform arbitrary additional
  44. site-specific customizations.  If this import fails with an
  45. ImportError exception, it is silently ignored.
  46. """
  47. import sys
  48. import os
  49. import __builtin__
  50. # Prefixes for site-packages; add additional prefixes like /usr/local here
  51. PREFIXES = [sys.prefix, sys.exec_prefix]
  52. # Enable per user site-packages directory
  53. # set it to False to disable the feature or True to force the feature
  54. ENABLE_USER_SITE = None
  55. # for distutils.commands.install
  56. USER_SITE = None
  57. USER_BASE = None
  58. def makepath(*paths):
  59.     dir = os.path.abspath(os.path.join(*paths))
  60.     return dir, os.path.normcase(dir)
  61. def abs__file__():
  62.     """Set all module' __file__ attribute to an absolute path"""
  63.     for m in sys.modules.values():
  64.         if hasattr(m, '__loader__'):
  65.             continue   # don't mess with a PEP 302-supplied __file__
  66.         try:
  67.             m.__file__ = os.path.abspath(m.__file__)
  68.         except AttributeError:
  69.             continue
  70. def removeduppaths():
  71.     """ Remove duplicate entries from sys.path along with making them
  72.     absolute"""
  73.     # This ensures that the initial path provided by the interpreter contains
  74.     # only absolute pathnames, even if we're running from the build directory.
  75.     L = []
  76.     known_paths = set()
  77.     for dir in sys.path:
  78.         # Filter out duplicate paths (on case-insensitive file systems also
  79.         # if they only differ in case); turn relative paths into absolute
  80.         # paths.
  81.         dir, dircase = makepath(dir)
  82.         if not dircase in known_paths:
  83.             L.append(dir)
  84.             known_paths.add(dircase)
  85.     sys.path[:] = L
  86.     return known_paths
  87. # XXX This should not be part of site.py, since it is needed even when
  88. # using the -S option for Python.  See http://www.python.org/sf/586680
  89. def addbuilddir():
  90.     """Append ./build/lib.<platform> in case we're running in the build dir
  91.     (especially for Guido :-)"""
  92.     from distutils.util import get_platform
  93.     s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
  94.     if hasattr(sys, 'gettotalrefcount'):
  95.         s += '-pydebug'
  96.     s = os.path.join(os.path.dirname(sys.path[-1]), s)
  97.     sys.path.append(s)
  98. def _init_pathinfo():
  99.     """Return a set containing all existing directory entries from sys.path"""
  100.     d = set()
  101.     for dir in sys.path:
  102.         try:
  103.             if os.path.isdir(dir):
  104.                 dir, dircase = makepath(dir)
  105.                 d.add(dircase)
  106.         except TypeError:
  107.             continue
  108.     return d
  109. def addpackage(sitedir, name, known_paths):
  110.     """Process a .pth file within the site-packages directory:
  111.        For each line in the file, either combine it with sitedir to a path
  112.        and add that to known_paths, or execute it if it starts with 'import '.
  113.     """
  114.     if known_paths is None:
  115.         _init_pathinfo()
  116.         reset = 1
  117.     else:
  118.         reset = 0
  119.     fullname = os.path.join(sitedir, name)
  120.     try:
  121.         f = open(fullname, "rU")
  122.     except IOError:
  123.         return
  124.     with f:
  125.         for line in f:
  126.             if line.startswith("#"):
  127.                 continue
  128.             if line.startswith(("import ", "importt")):
  129.                 exec line
  130.                 continue
  131.             line = line.rstrip()
  132.             dir, dircase = makepath(sitedir, line)
  133.             if not dircase in known_paths and os.path.exists(dir):
  134.                 sys.path.append(dir)
  135.                 known_paths.add(dircase)
  136.     if reset:
  137.         known_paths = None
  138.     return known_paths
  139. def addsitedir(sitedir, known_paths=None):
  140.     """Add 'sitedir' argument to sys.path if missing and handle .pth files in
  141.     'sitedir'"""
  142.     if known_paths is None:
  143.         known_paths = _init_pathinfo()
  144.         reset = 1
  145.     else:
  146.         reset = 0
  147.     sitedir, sitedircase = makepath(sitedir)
  148.     if not sitedircase in known_paths:
  149.         sys.path.append(sitedir)        # Add path component
  150.     try:
  151.         names = os.listdir(sitedir)
  152.     except os.error:
  153.         return
  154.     dotpth = os.extsep + "pth"
  155.     names = [name for name in names if name.endswith(dotpth)]
  156.     for name in sorted(names):
  157.         addpackage(sitedir, name, known_paths)
  158.     if reset:
  159.         known_paths = None
  160.     return known_paths
  161. def check_enableusersite():
  162.     """Check if user site directory is safe for inclusion
  163.     The function tests for the command line flag (including environment var),
  164.     process uid/gid equal to effective uid/gid.
  165.     None: Disabled for security reasons
  166.     False: Disabled by user (command line option)
  167.     True: Safe and enabled
  168.     """
  169.     if sys.flags.no_user_site:
  170.         return False
  171.     if hasattr(os, "getuid") and hasattr(os, "geteuid"):
  172.         # check process uid == effective uid
  173.         if os.geteuid() != os.getuid():
  174.             return None
  175.     if hasattr(os, "getgid") and hasattr(os, "getegid"):
  176.         # check process gid == effective gid
  177.         if os.getegid() != os.getgid():
  178.             return None
  179.     return True
  180. def addusersitepackages(known_paths):
  181.     """Add a per user site-package to sys.path
  182.     Each user has its own python directory with site-packages in the
  183.     home directory.
  184.     USER_BASE is the root directory for all Python versions
  185.     USER_SITE is the user specific site-packages directory
  186.     USER_SITE/.. can be used for data.
  187.     """
  188.     global USER_BASE, USER_SITE, ENABLE_USER_SITE
  189.     env_base = os.environ.get("PYTHONUSERBASE", None)
  190.     def joinuser(*args):
  191.         return os.path.expanduser(os.path.join(*args))
  192.     #if sys.platform in ('os2emx', 'riscos'):
  193.     #    # Don't know what to put here
  194.     #    USER_BASE = ''
  195.     #    USER_SITE = ''
  196.     if os.name == "nt":
  197.         base = os.environ.get("APPDATA") or "~"
  198.         USER_BASE = env_base if env_base else joinuser(base, "Python")
  199.         USER_SITE = os.path.join(USER_BASE,
  200.                                  "Python" + sys.version[0] + sys.version[2],
  201.                                  "site-packages")
  202.     else:
  203.         USER_BASE = env_base if env_base else joinuser("~", ".local")
  204.         USER_SITE = os.path.join(USER_BASE, "lib",
  205.                                  "python" + sys.version[:3],
  206.                                  "site-packages")
  207.     if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
  208.         addsitedir(USER_SITE, known_paths)
  209.     return known_paths
  210. def addsitepackages(known_paths):
  211.     """Add site-packages (and possibly site-python) to sys.path"""
  212.     sitedirs = []
  213.     seen = []
  214.     for prefix in PREFIXES:
  215.         if not prefix or prefix in seen:
  216.             continue
  217.         seen.append(prefix)
  218.         if sys.platform in ('os2emx', 'riscos'):
  219.             sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
  220.         elif os.sep == '/':
  221.             sitedirs.append(os.path.join(prefix, "lib",
  222.                                         "python" + sys.version[:3],
  223.                                         "site-packages"))
  224.             sitedirs.append(os.path.join(prefix, "lib", "site-python"))
  225.         else:
  226.             sitedirs.append(prefix)
  227.             sitedirs.append(os.path.join(prefix, "lib", "site-packages"))
  228.         if sys.platform == "darwin":
  229.             # for framework builds *only* we add the standard Apple
  230.             # locations. Currently only per-user, but /Library and
  231.             # /Network/Library could be added too
  232.             if 'Python.framework' in prefix:
  233.                 sitedirs.append(
  234.                     os.path.expanduser(
  235.                         os.path.join("~", "Library", "Python",
  236.                                      sys.version[:3], "site-packages")))
  237.     for sitedir in sitedirs:
  238.         if os.path.isdir(sitedir):
  239.             addsitedir(sitedir, known_paths)
  240.     return known_paths
  241. def setBEGINLIBPATH():
  242.     """The OS/2 EMX port has optional extension modules that do double duty
  243.     as DLLs (and must use the .DLL file extension) for other extensions.
  244.     The library search path needs to be amended so these will be found
  245.     during module import.  Use BEGINLIBPATH so that these are at the start
  246.     of the library search path.
  247.     """
  248.     dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
  249.     libpath = os.environ['BEGINLIBPATH'].split(';')
  250.     if libpath[-1]:
  251.         libpath.append(dllpath)
  252.     else:
  253.         libpath[-1] = dllpath
  254.     os.environ['BEGINLIBPATH'] = ';'.join(libpath)
  255. def setquit():
  256.     """Define new built-ins 'quit' and 'exit'.
  257.     These are simply strings that display a hint on how to exit.
  258.     """
  259.     if os.sep == ':':
  260.         eof = 'Cmd-Q'
  261.     elif os.sep == '\':
  262.         eof = 'Ctrl-Z plus Return'
  263.     else:
  264.         eof = 'Ctrl-D (i.e. EOF)'
  265.     class Quitter(object):
  266.         def __init__(self, name):
  267.             self.name = name
  268.         def __repr__(self):
  269.             return 'Use %s() or %s to exit' % (self.name, eof)
  270.         def __call__(self, code=None):
  271.             # Shells like IDLE catch the SystemExit, but listen when their
  272.             # stdin wrapper is closed.
  273.             try:
  274.                 sys.stdin.close()
  275.             except:
  276.                 pass
  277.             raise SystemExit(code)
  278.     __builtin__.quit = Quitter('quit')
  279.     __builtin__.exit = Quitter('exit')
  280. class _Printer(object):
  281.     """interactive prompt objects for printing the license text, a list of
  282.     contributors and the copyright notice."""
  283.     MAXLINES = 23
  284.     def __init__(self, name, data, files=(), dirs=()):
  285.         self.__name = name
  286.         self.__data = data
  287.         self.__files = files
  288.         self.__dirs = dirs
  289.         self.__lines = None
  290.     def __setup(self):
  291.         if self.__lines:
  292.             return
  293.         data = None
  294.         for dir in self.__dirs:
  295.             for filename in self.__files:
  296.                 filename = os.path.join(dir, filename)
  297.                 try:
  298.                     fp = file(filename, "rU")
  299.                     data = fp.read()
  300.                     fp.close()
  301.                     break
  302.                 except IOError:
  303.                     pass
  304.             if data:
  305.                 break
  306.         if not data:
  307.             data = self.__data
  308.         self.__lines = data.split('n')
  309.         self.__linecnt = len(self.__lines)
  310.     def __repr__(self):
  311.         self.__setup()
  312.         if len(self.__lines) <= self.MAXLINES:
  313.             return "n".join(self.__lines)
  314.         else:
  315.             return "Type %s() to see the full %s text" % ((self.__name,)*2)
  316.     def __call__(self):
  317.         self.__setup()
  318.         prompt = 'Hit Return for more, or q (and Return) to quit: '
  319.         lineno = 0
  320.         while 1:
  321.             try:
  322.                 for i in range(lineno, lineno + self.MAXLINES):
  323.                     print self.__lines[i]
  324.             except IndexError:
  325.                 break
  326.             else:
  327.                 lineno += self.MAXLINES
  328.                 key = None
  329.                 while key is None:
  330.                     key = raw_input(prompt)
  331.                     if key not in ('', 'q'):
  332.                         key = None
  333.                 if key == 'q':
  334.                     break
  335. def setcopyright():
  336.     """Set 'copyright' and 'credits' in __builtin__"""
  337.     __builtin__.copyright = _Printer("copyright", sys.copyright)
  338.     if sys.platform[:4] == 'java':
  339.         __builtin__.credits = _Printer(
  340.             "credits",
  341.             "Jython is maintained by the Jython developers (www.jython.org).")
  342.     else:
  343.         __builtin__.credits = _Printer("credits", """
  344.     ActivePython is a Python distribution by ActiveState Software Inc.
  345.     Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
  346.     for supporting Python development.  See www.python.org for more information.""")
  347.     here = os.path.dirname(os.__file__)
  348.     __builtin__.license = _Printer(
  349.         "license",
  350.         "See http://www.ActiveState.com/Products/ActivePython/license_agreement.plex",
  351.         ["LICENSE.txt", "LICENSE", "License.txt"],
  352.         [os.path.join(here, os.pardir, "Doc"), # dev build and installation on Windows
  353.          os.path.join(here, os.pardir, os.pardir, "doc", # APy install on Linux
  354.                       "python%s.%s" % sys.version_info[:2]),
  355.          # APy install on Mac OS X
  356.          os.path.join(here, os.pardir, os.pardir, "Resources",
  357.                       "Python.app", "Contents", "Resources", "English.lproj",
  358.                       "Help"),
  359.          here]) # dev build on Linux
  360. class _Helper(object):
  361.     """Define the built-in 'help'.
  362.     This is a wrapper around pydoc.help (with a twist).
  363.     """
  364.     def __repr__(self):
  365.         return "Type help() for interactive help, " 
  366.                "or help(object) for help about object."
  367.     def __call__(self, *args, **kwds):
  368.         import pydoc
  369.         return pydoc.help(*args, **kwds)
  370. def sethelper():
  371.     __builtin__.help = _Helper()
  372. def aliasmbcs():
  373.     """On Windows, some default encodings are not provided by Python,
  374.     while they are always available as "mbcs" in each locale. Make
  375.     them usable by aliasing to "mbcs" in such a case."""
  376.     if sys.platform == 'win32':
  377.         import locale, codecs
  378.         enc = locale.getdefaultlocale()[1]
  379.         if enc.startswith('cp'):            # "cp***" ?
  380.             try:
  381.                 codecs.lookup(enc)
  382.             except LookupError:
  383.                 import encodings
  384.                 encodings._cache[enc] = encodings._unknown
  385.                 encodings.aliases.aliases[enc] = 'mbcs'
  386. def setencoding():
  387.     """Set the string encoding used by the Unicode implementation.  The
  388.     default is 'ascii', but if you're willing to experiment, you can
  389.     change this."""
  390.     encoding = "ascii" # Default value set by _PyUnicode_Init()
  391.     if 0:
  392.         # Enable to support locale aware default string encodings.
  393.         import locale
  394.         loc = locale.getdefaultlocale()
  395.         if loc[1]:
  396.             encoding = loc[1]
  397.     if 0:
  398.         # Enable to switch off string to Unicode coercion and implicit
  399.         # Unicode to string conversion.
  400.         encoding = "undefined"
  401.     if encoding != "ascii":
  402.         # On Non-Unicode builds this will raise an AttributeError...
  403.         sys.setdefaultencoding(encoding) # Needs Python Unicode build !
  404. def execsitecustomize():
  405.     """Run custom site specific code, if available."""
  406.     try:
  407.         import sitecustomize
  408.     except ImportError:
  409.         pass
  410. def execusercustomize():
  411.     """Run custom user specific code, if available."""
  412.     try:
  413.         import usercustomize
  414.     except ImportError:
  415.         pass
  416. def main():
  417.     global ENABLE_USER_SITE
  418.     abs__file__()
  419.     known_paths = removeduppaths()
  420.     if (os.name == "posix" and sys.path and
  421.         os.path.basename(sys.path[-1]) == "Modules"):
  422.         addbuilddir()
  423.     if ENABLE_USER_SITE is None:
  424.         ENABLE_USER_SITE = check_enableusersite()
  425.     known_paths = addusersitepackages(known_paths)
  426.     known_paths = addsitepackages(known_paths)
  427.     if sys.platform == 'os2emx':
  428.         setBEGINLIBPATH()
  429.     setquit()
  430.     setcopyright()
  431.     sethelper()
  432.     aliasmbcs()
  433.     setencoding()
  434.     execsitecustomize()
  435.     if ENABLE_USER_SITE:
  436.         execusercustomize()
  437.     # Remove sys.setdefaultencoding() so that users cannot change the
  438.     # encoding after initialization.  The test for presence is needed when
  439.     # this module is run as a script, because this code is executed twice.
  440.     if hasattr(sys, "setdefaultencoding"):
  441.         del sys.setdefaultencoding
  442. main()
  443. def _script():
  444.     help = """
  445.     %s [--user-base] [--user-site]
  446.     Without arguments print some useful information
  447.     With arguments print the value of USER_BASE and/or USER_SITE separated
  448.     by '%s'.
  449.     Exit codes with --user-base or --user-site:
  450.       0 - user site directory is enabled
  451.       1 - user site directory is disabled by user
  452.       2 - uses site directory is disabled by super user
  453.           or for security reasons
  454.      >2 - unknown error
  455.     """
  456.     args = sys.argv[1:]
  457.     if not args:
  458.         print "sys.path = ["
  459.         for dir in sys.path:
  460.             print "    %r," % (dir,)
  461.         print "]"
  462.         print "USER_BASE: %r (%s)" % (USER_BASE,
  463.             "exists" if os.path.isdir(USER_BASE) else "doesn't exist")
  464.         print "USER_SITE: %r (%s)" % (USER_SITE,
  465.             "exists" if os.path.isdir(USER_SITE) else "doesn't exist")
  466.         print "ENABLE_USER_SITE: %r" %  ENABLE_USER_SITE
  467.         sys.exit(0)
  468.     buffer = []
  469.     if '--user-base' in args:
  470.         buffer.append(USER_BASE)
  471.     if '--user-site' in args:
  472.         buffer.append(USER_SITE)
  473.     if buffer:
  474.         print os.pathsep.join(buffer)
  475.         if ENABLE_USER_SITE:
  476.             sys.exit(0)
  477.         elif ENABLE_USER_SITE is False:
  478.             sys.exit(1)
  479.         elif ENABLE_USER_SITE is None:
  480.             sys.exit(2)
  481.         else:
  482.             sys.exit(3)
  483.     else:
  484.         import textwrap
  485.         print textwrap.dedent(help % (sys.argv[0], os.pathsep))
  486.         sys.exit(10)
  487. if __name__ == '__main__':
  488.     _script()