Advertisement
Guest User

site.py

a guest
Jun 7th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 27.64 KB | None | 0 0
  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 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. It also supports the Debian convention of
  17. lib/python<version>/dist-packages.  On other platforms (mainly Mac and
  18. Windows), it uses just sys.prefix (and sys.exec_prefix, if different,
  19. but this is unlikely).  The resulting directories, if they exist, are
  20. appended to sys.path, and also inspected for path configuration files.
  21.  
  22. FOR DEBIAN, this sys.path is augmented with directories in /usr/local.
  23. Local addons go into /usr/local/lib/python<version>/site-packages
  24. (resp. /usr/local/lib/site-python), Debian addons install into
  25. /usr/{lib,share}/python<version>/dist-packages.
  26.  
  27. A path configuration file is a file whose name has the form
  28. <package>.pth; its contents are additional directories (one per line)
  29. to be added to sys.path.  Non-existing directories (or
  30. non-directories) are never added to sys.path; no directory is added to
  31. sys.path more than once.  Blank lines and lines beginning with
  32. '#' are skipped. Lines starting with 'import' are executed.
  33.  
  34. For example, suppose sys.prefix and sys.exec_prefix are set to
  35. /usr/local and there is a directory /usr/local/lib/python2.X/site-packages
  36. with three subdirectories, foo, bar and spam, and two path
  37. configuration files, foo.pth and bar.pth.  Assume foo.pth contains the
  38. following:
  39.  
  40.  # foo package configuration
  41.  foo
  42.  bar
  43.  bletch
  44.  
  45. and bar.pth contains:
  46.  
  47.  # bar package configuration
  48.  bar
  49.  
  50. Then the following directories are added to sys.path, in this order:
  51.  
  52.  /usr/local/lib/python2.X/site-packages/bar
  53.  /usr/local/lib/python2.X/site-packages/foo
  54.  
  55. Note that bletch is omitted because it doesn't exist; bar precedes foo
  56. because bar.pth comes alphabetically before foo.pth; and spam is
  57. omitted because it is not mentioned in either path configuration file.
  58.  
  59. After these path manipulations, an attempt is made to import a module
  60. named sitecustomize, which can perform arbitrary additional
  61. site-specific customizations.  If this import fails with an
  62. ImportError exception, it is silently ignored.
  63.  
  64. """
  65.  
  66. import sys
  67. import os
  68. try:
  69.     import __builtin__ as builtins
  70. except ImportError:
  71.     import builtins
  72. try:
  73.     set
  74. except NameError:
  75.     from sets import Set as set
  76.  
  77. # Prefixes for site-packages; add additional prefixes like /usr/local here
  78. PREFIXES = [sys.prefix, sys.exec_prefix]
  79. # Enable per user site-packages directory
  80. # set it to False to disable the feature or True to force the feature
  81. ENABLE_USER_SITE = None
  82. # for distutils.commands.install
  83. USER_SITE = None
  84. USER_BASE = None
  85.  
  86. _is_64bit = (getattr(sys, 'maxsize', None) or getattr(sys, 'maxint')) > 2**32
  87. _is_pypy = hasattr(sys, 'pypy_version_info')
  88. _is_jython = sys.platform[:4] == 'java'
  89. if _is_jython:
  90.     ModuleType = type(os)
  91.  
  92. def makepath(*paths):
  93.     dir = os.path.join(*paths)
  94.     if _is_jython and (dir == '__classpath__' or
  95.                        dir.startswith('__pyclasspath__')):
  96.         return dir, dir
  97.     dir = os.path.abspath(dir)
  98.     return dir, os.path.normcase(dir)
  99.  
  100. def abs__file__():
  101.     """Set all module' __file__ attribute to an absolute path"""
  102.     for m in sys.modules.values():
  103.         if ((_is_jython and not isinstance(m, ModuleType)) or
  104.             hasattr(m, '__loader__')):
  105.             # only modules need the abspath in Jython. and don't mess
  106.             # with a PEP 302-supplied __file__
  107.             continue
  108.         f = getattr(m, '__file__', None)
  109.         if f is None:
  110.             continue
  111.         m.__file__ = os.path.abspath(f)
  112.  
  113. def removeduppaths():
  114.     """ Remove duplicate entries from sys.path along with making them
  115.    absolute"""
  116.     # This ensures that the initial path provided by the interpreter contains
  117.     # only absolute pathnames, even if we're running from the build directory.
  118.     L = []
  119.     known_paths = set()
  120.     for dir in sys.path:
  121.         # Filter out duplicate paths (on case-insensitive file systems also
  122.         # if they only differ in case); turn relative paths into absolute
  123.         # paths.
  124.         dir, dircase = makepath(dir)
  125.         if not dircase in known_paths:
  126.             L.append(dir)
  127.             known_paths.add(dircase)
  128.     sys.path[:] = L
  129.     return known_paths
  130.  
  131. # XXX This should not be part of site.py, since it is needed even when
  132. # using the -S option for Python.  See http://www.python.org/sf/586680
  133. def addbuilddir():
  134.     """Append ./build/lib.<platform> in case we're running in the build dir
  135.    (especially for Guido :-)"""
  136.     from distutils.util import get_platform
  137.     s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
  138.     if hasattr(sys, 'gettotalrefcount'):
  139.         s += '-pydebug'
  140.     s = os.path.join(os.path.dirname(sys.path[-1]), s)
  141.     sys.path.append(s)
  142.  
  143. def _init_pathinfo():
  144.     """Return a set containing all existing directory entries from sys.path"""
  145.     d = set()
  146.     for dir in sys.path:
  147.         try:
  148.             if os.path.isdir(dir):
  149.                 dir, dircase = makepath(dir)
  150.                 d.add(dircase)
  151.         except TypeError:
  152.             continue
  153.     return d
  154.  
  155. def addpackage(sitedir, name, known_paths):
  156.     """Add a new path to known_paths by combining sitedir and 'name' or execute
  157.    sitedir if it starts with 'import'"""
  158.     if known_paths is None:
  159.         _init_pathinfo()
  160.         reset = 1
  161.     else:
  162.         reset = 0
  163.     fullname = os.path.join(sitedir, name)
  164.     try:
  165.         f = open(fullname, "rU")
  166.     except IOError:
  167.         return
  168.     try:
  169.         for line in f:
  170.             if line.startswith("#"):
  171.                 continue
  172.             if line.startswith("import"):
  173.                 exec(line)
  174.                 continue
  175.             line = line.rstrip()
  176.             dir, dircase = makepath(sitedir, line)
  177.             if not dircase in known_paths and os.path.exists(dir):
  178.                 sys.path.append(dir)
  179.                 known_paths.add(dircase)
  180.     finally:
  181.         f.close()
  182.     if reset:
  183.         known_paths = None
  184.     return known_paths
  185.  
  186. def addsitedir(sitedir, known_paths=None):
  187.     """Add 'sitedir' argument to sys.path if missing and handle .pth files in
  188.    'sitedir'"""
  189.     if known_paths is None:
  190.         known_paths = _init_pathinfo()
  191.         reset = 1
  192.     else:
  193.         reset = 0
  194.     sitedir, sitedircase = makepath(sitedir)
  195.     if not sitedircase in known_paths:
  196.         sys.path.append(sitedir)        # Add path component
  197.     try:
  198.         names = os.listdir(sitedir)
  199.     except os.error:
  200.         return
  201.     names.sort()
  202.     for name in names:
  203.         if name.endswith(os.extsep + "pth"):
  204.             addpackage(sitedir, name, known_paths)
  205.     if reset:
  206.         known_paths = None
  207.     return known_paths
  208.  
  209. def addsitepackages(known_paths, sys_prefix=sys.prefix, exec_prefix=sys.exec_prefix):
  210.     """Add site-packages (and possibly site-python) to sys.path"""
  211.     prefixes = [os.path.join(sys_prefix, "local"), sys_prefix]
  212.     if exec_prefix != sys_prefix:
  213.         prefixes.append(os.path.join(exec_prefix, "local"))
  214.  
  215.     for prefix in prefixes:
  216.         if prefix:
  217.             if sys.platform in ('os2emx', 'riscos') or _is_jython:
  218.                 sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
  219.             elif _is_pypy:
  220.                 sitedirs = [os.path.join(prefix, 'site-packages')]
  221.             elif sys.platform == 'darwin' and prefix == sys_prefix:
  222.  
  223.                 if prefix.startswith("/System/Library/Frameworks/"): # Apple's Python
  224.  
  225.                     sitedirs = [os.path.join("/Library/Python", sys.version[:3], "site-packages"),
  226.                                 os.path.join(prefix, "Extras", "lib", "python")]
  227.  
  228.                 else: # any other Python distros on OSX work this way
  229.                     sitedirs = [os.path.join(prefix, "lib",
  230.                                              "python" + sys.version[:3], "site-packages")]
  231.  
  232.             elif os.sep == '/':
  233.                 sitedirs = [os.path.join(prefix,
  234.                                          "lib",
  235.                                          "python" + sys.version[:3],
  236.                                          "site-packages"),
  237.                             os.path.join(prefix, "lib", "site-python"),
  238.                             os.path.join(prefix, "python" + sys.version[:3], "lib-dynload")]
  239.                 lib64_dir = os.path.join(prefix, "lib64", "python" + sys.version[:3], "site-packages")
  240.                 if (os.path.exists(lib64_dir) and
  241.                     os.path.realpath(lib64_dir) not in [os.path.realpath(p) for p in sitedirs]):
  242.                     if _is_64bit:
  243.                         sitedirs.insert(0, lib64_dir)
  244.                     else:
  245.                         sitedirs.append(lib64_dir)
  246.                 try:
  247.                     # sys.getobjects only available in --with-pydebug build
  248.                     sys.getobjects
  249.                     sitedirs.insert(0, os.path.join(sitedirs[0], 'debug'))
  250.                 except AttributeError:
  251.                     pass
  252.                 # Debian-specific dist-packages directories:
  253.                 if sys.version[0] == '2':
  254.                     sitedirs.append(os.path.join(prefix, "lib",
  255.                                                  "python" + sys.version[:3],
  256.                                                  "dist-packages"))
  257.                 else:
  258.                     sitedirs.append(os.path.join(prefix, "lib",
  259.                                                  "python" + sys.version[0],
  260.                                                  "dist-packages"))
  261.                 sitedirs.append(os.path.join(prefix, "local/lib",
  262.                                              "python" + sys.version[:3],
  263.                                              "dist-packages"))
  264.                 sitedirs.append(os.path.join(prefix, "lib", "dist-python"))
  265.             else:
  266.                 sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
  267.             if sys.platform == 'darwin':
  268.                 # for framework builds *only* we add the standard Apple
  269.                 # locations. Currently only per-user, but /Library and
  270.                 # /Network/Library could be added too
  271.                 if 'Python.framework' in prefix:
  272.                     home = os.environ.get('HOME')
  273.                     if home:
  274.                         sitedirs.append(
  275.                             os.path.join(home,
  276.                                          'Library',
  277.                                          'Python',
  278.                                          sys.version[:3],
  279.                                          'site-packages'))
  280.             for sitedir in sitedirs:
  281.                 if os.path.isdir(sitedir):
  282.                     addsitedir(sitedir, known_paths)
  283.     return None
  284.  
  285. def check_enableusersite():
  286.     """Check if user site directory is safe for inclusion
  287.  
  288.    The function tests for the command line flag (including environment var),
  289.    process uid/gid equal to effective uid/gid.
  290.  
  291.    None: Disabled for security reasons
  292.    False: Disabled by user (command line option)
  293.    True: Safe and enabled
  294.    """
  295.     if hasattr(sys, 'flags') and getattr(sys.flags, 'no_user_site', False):
  296.         return False
  297.  
  298.     if hasattr(os, "getuid") and hasattr(os, "geteuid"):
  299.         # check process uid == effective uid
  300.         if os.geteuid() != os.getuid():
  301.             return None
  302.     if hasattr(os, "getgid") and hasattr(os, "getegid"):
  303.         # check process gid == effective gid
  304.         if os.getegid() != os.getgid():
  305.             return None
  306.  
  307.     return True
  308.  
  309. def addusersitepackages(known_paths):
  310.     """Add a per user site-package to sys.path
  311.  
  312.    Each user has its own python directory with site-packages in the
  313.    home directory.
  314.  
  315.    USER_BASE is the root directory for all Python versions
  316.  
  317.    USER_SITE is the user specific site-packages directory
  318.  
  319.    USER_SITE/.. can be used for data.
  320.    """
  321.     global USER_BASE, USER_SITE, ENABLE_USER_SITE
  322.     env_base = os.environ.get("PYTHONUSERBASE", None)
  323.  
  324.     def joinuser(*args):
  325.         return os.path.expanduser(os.path.join(*args))
  326.  
  327.     #if sys.platform in ('os2emx', 'riscos'):
  328.     #    # Don't know what to put here
  329.     #    USER_BASE = ''
  330.     #    USER_SITE = ''
  331.     if os.name == "nt":
  332.         base = os.environ.get("APPDATA") or "~"
  333.         if env_base:
  334.             USER_BASE = env_base
  335.         else:
  336.             USER_BASE = joinuser(base, "Python")
  337.         USER_SITE = os.path.join(USER_BASE,
  338.                                  "Python" + sys.version[0] + sys.version[2],
  339.                                  "site-packages")
  340.     else:
  341.         if env_base:
  342.             USER_BASE = env_base
  343.         else:
  344.             USER_BASE = joinuser("~", ".local")
  345.         USER_SITE = os.path.join(USER_BASE, "lib",
  346.                                  "python" + sys.version[:3],
  347.                                  "site-packages")
  348.  
  349.     if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
  350.         addsitedir(USER_SITE, known_paths)
  351.     if ENABLE_USER_SITE:
  352.         for dist_libdir in ("lib", "local/lib"):
  353.             user_site = os.path.join(USER_BASE, dist_libdir,
  354.                                      "python" + sys.version[:3],
  355.                                      "dist-packages")
  356.             if os.path.isdir(user_site):
  357.                 addsitedir(user_site, known_paths)
  358.     return known_paths
  359.  
  360.  
  361.  
  362. def setBEGINLIBPATH():
  363.     """The OS/2 EMX port has optional extension modules that do double duty
  364.    as DLLs (and must use the .DLL file extension) for other extensions.
  365.    The library search path needs to be amended so these will be found
  366.    during module import.  Use BEGINLIBPATH so that these are at the start
  367.    of the library search path.
  368.  
  369.    """
  370.     dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
  371.     libpath = os.environ['BEGINLIBPATH'].split(';')
  372.     if libpath[-1]:
  373.         libpath.append(dllpath)
  374.     else:
  375.         libpath[-1] = dllpath
  376.     os.environ['BEGINLIBPATH'] = ';'.join(libpath)
  377.  
  378.  
  379. def setquit():
  380.     """Define new built-ins 'quit' and 'exit'.
  381.    These are simply strings that display a hint on how to exit.
  382.  
  383.    """
  384.     if os.sep == ':':
  385.         eof = 'Cmd-Q'
  386.     elif os.sep == '\\':
  387.         eof = 'Ctrl-Z plus Return'
  388.     else:
  389.         eof = 'Ctrl-D (i.e. EOF)'
  390.  
  391.     class Quitter(object):
  392.         def __init__(self, name):
  393.             self.name = name
  394.         def __repr__(self):
  395.             return 'Use %s() or %s to exit' % (self.name, eof)
  396.         def __call__(self, code=None):
  397.             # Shells like IDLE catch the SystemExit, but listen when their
  398.             # stdin wrapper is closed.
  399.             try:
  400.                 sys.stdin.close()
  401.             except:
  402.                 pass
  403.             raise SystemExit(code)
  404.     builtins.quit = Quitter('quit')
  405.     builtins.exit = Quitter('exit')
  406.  
  407.  
  408. class _Printer(object):
  409.     """interactive prompt objects for printing the license text, a list of
  410.    contributors and the copyright notice."""
  411.  
  412.     MAXLINES = 23
  413.  
  414.     def __init__(self, name, data, files=(), dirs=()):
  415.         self.__name = name
  416.         self.__data = data
  417.         self.__files = files
  418.         self.__dirs = dirs
  419.         self.__lines = None
  420.  
  421.     def __setup(self):
  422.         if self.__lines:
  423.             return
  424.         data = None
  425.         for dir in self.__dirs:
  426.             for filename in self.__files:
  427.                 filename = os.path.join(dir, filename)
  428.                 try:
  429.                     fp = open(filename, "rU")
  430.                     data = fp.read()
  431.                     fp.close()
  432.                     break
  433.                 except IOError:
  434.                     pass
  435.             if data:
  436.                 break
  437.         if not data:
  438.             data = self.__data
  439.         self.__lines = data.split('\n')
  440.         self.__linecnt = len(self.__lines)
  441.  
  442.     def __repr__(self):
  443.         self.__setup()
  444.         if len(self.__lines) <= self.MAXLINES:
  445.             return "\n".join(self.__lines)
  446.         else:
  447.             return "Type %s() to see the full %s text" % ((self.__name,)*2)
  448.  
  449.     def __call__(self):
  450.         self.__setup()
  451.         prompt = 'Hit Return for more, or q (and Return) to quit: '
  452.         lineno = 0
  453.         while 1:
  454.             try:
  455.                 for i in range(lineno, lineno + self.MAXLINES):
  456.                     print(self.__lines[i])
  457.             except IndexError:
  458.                 break
  459.             else:
  460.                 lineno += self.MAXLINES
  461.                 key = None
  462.                 while key is None:
  463.                     try:
  464.                         key = raw_input(prompt)
  465.                     except NameError:
  466.                         key = input(prompt)
  467.                     if key not in ('', 'q'):
  468.                         key = None
  469.                 if key == 'q':
  470.                     break
  471.  
  472. def setcopyright():
  473.     """Set 'copyright' and 'credits' in __builtin__"""
  474.     builtins.copyright = _Printer("copyright", sys.copyright)
  475.     if _is_jython:
  476.         builtins.credits = _Printer(
  477.             "credits",
  478.             "Jython is maintained by the Jython developers (www.jython.org).")
  479.     elif _is_pypy:
  480.         builtins.credits = _Printer(
  481.             "credits",
  482.             "PyPy is maintained by the PyPy developers: http://pypy.org/")
  483.     else:
  484.         builtins.credits = _Printer("credits", """\
  485.    Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
  486.    for supporting Python development.  See www.python.org for more information.""")
  487.     here = os.path.dirname(os.__file__)
  488.     builtins.license = _Printer(
  489.         "license", "See http://www.python.org/%.3s/license.html" % sys.version,
  490.         ["LICENSE.txt", "LICENSE"],
  491.         [os.path.join(here, os.pardir), here, os.curdir])
  492.  
  493.  
  494. class _Helper(object):
  495.     """Define the built-in 'help'.
  496.    This is a wrapper around pydoc.help (with a twist).
  497.  
  498.    """
  499.  
  500.     def __repr__(self):
  501.         return "Type help() for interactive help, " \
  502.                "or help(object) for help about object."
  503.     def __call__(self, *args, **kwds):
  504.         import pydoc
  505.         return pydoc.help(*args, **kwds)
  506.  
  507. def sethelper():
  508.     builtins.help = _Helper()
  509.  
  510. def aliasmbcs():
  511.     """On Windows, some default encodings are not provided by Python,
  512.    while they are always available as "mbcs" in each locale. Make
  513.    them usable by aliasing to "mbcs" in such a case."""
  514.     if sys.platform == 'win32':
  515.         import locale, codecs
  516.         enc = locale.getdefaultlocale()[1]
  517.         if enc.startswith('cp'):            # "cp***" ?
  518.             try:
  519.                 codecs.lookup(enc)
  520.             except LookupError:
  521.                 import encodings
  522.                 encodings._cache[enc] = encodings._unknown
  523.                 encodings.aliases.aliases[enc] = 'mbcs'
  524.  
  525. def setencoding():
  526.     """Set the string encoding used by the Unicode implementation.  The
  527.    default is 'ascii', but if you're willing to experiment, you can
  528.    change this."""
  529.     encoding = "ascii" # Default value set by _PyUnicode_Init()
  530.     if 0:
  531.         # Enable to support locale aware default string encodings.
  532.         import locale
  533.         loc = locale.getdefaultlocale()
  534.         if loc[1]:
  535.             encoding = loc[1]
  536.     if 0:
  537.         # Enable to switch off string to Unicode coercion and implicit
  538.         # Unicode to string conversion.
  539.         encoding = "undefined"
  540.     if encoding != "ascii":
  541.         # On Non-Unicode builds this will raise an AttributeError...
  542.         sys.setdefaultencoding(encoding) # Needs Python Unicode build !
  543.  
  544.  
  545. def execsitecustomize():
  546.     """Run custom site specific code, if available."""
  547.     try:
  548.         import sitecustomize
  549.     except ImportError:
  550.         pass
  551.  
  552. def virtual_install_main_packages():
  553.     f = open(os.path.join(os.path.dirname(__file__), 'orig-prefix.txt'))
  554.     sys.real_prefix = f.read().strip()
  555.     f.close()
  556.     pos = 2
  557.     hardcoded_relative_dirs = []
  558.     if sys.path[0] == '':
  559.         pos += 1
  560.     if _is_jython:
  561.         paths = [os.path.join(sys.real_prefix, 'Lib')]
  562.     elif _is_pypy:
  563.         if sys.version_info > (3, 2):
  564.             cpyver = '%d' % sys.version_info[0]
  565.         elif sys.pypy_version_info >= (1, 5):
  566.             cpyver = '%d.%d' % sys.version_info[:2]
  567.         else:
  568.             cpyver = '%d.%d.%d' % sys.version_info[:3]
  569.         paths = [os.path.join(sys.real_prefix, 'lib_pypy'),
  570.                  os.path.join(sys.real_prefix, 'lib-python', cpyver)]
  571.         if sys.pypy_version_info < (1, 9):
  572.             paths.insert(1, os.path.join(sys.real_prefix,
  573.                                          'lib-python', 'modified-%s' % cpyver))
  574.         hardcoded_relative_dirs = paths[:] # for the special 'darwin' case below
  575.         #
  576.         # This is hardcoded in the Python executable, but relative to sys.prefix:
  577.         for path in paths[:]:
  578.             plat_path = os.path.join(path, 'plat-%s' % sys.platform)
  579.             if os.path.exists(plat_path):
  580.                 paths.append(plat_path)
  581.     elif sys.platform == 'win32':
  582.         paths = [os.path.join(sys.real_prefix, 'Lib'), os.path.join(sys.real_prefix, 'DLLs')]
  583.     else:
  584.         paths = [os.path.join(sys.real_prefix, 'lib', 'python'+sys.version[:3])]
  585.         hardcoded_relative_dirs = paths[:] # for the special 'darwin' case below
  586.         lib64_path = os.path.join(sys.real_prefix, 'lib64', 'python'+sys.version[:3])
  587.         if os.path.exists(lib64_path):
  588.             if _is_64bit:
  589.                 paths.insert(0, lib64_path)
  590.             else:
  591.                 paths.append(lib64_path)
  592.         # This is hardcoded in the Python executable, but relative to
  593.         # sys.prefix.  Debian change: we need to add the multiarch triplet
  594.         # here, which is where the real stuff lives.  As per PEP 421, in
  595.         # Python 3.3+, this lives in sys.implementation, while in Python 2.7
  596.         # it lives in sys.
  597.         try:
  598.             arch = getattr(sys, 'implementation', sys)._multiarch
  599.         except AttributeError:
  600.             # This is a non-multiarch aware Python.  Fallback to the old way.
  601.             arch = sys.platform
  602.         plat_path = os.path.join(sys.real_prefix, 'lib',
  603.                                  'python'+sys.version[:3],
  604.                                  'plat-%s' % arch)
  605.         if os.path.exists(plat_path):
  606.             paths.append(plat_path)
  607.     # This is hardcoded in the Python executable, but
  608.     # relative to sys.prefix, so we have to fix up:
  609.     for path in list(paths):
  610.         tk_dir = os.path.join(path, 'lib-tk')
  611.         if os.path.exists(tk_dir):
  612.             paths.append(tk_dir)
  613.  
  614.     # These are hardcoded in the Apple's Python executable,
  615.     # but relative to sys.prefix, so we have to fix them up:
  616.     if sys.platform == 'darwin':
  617.         hardcoded_paths = [os.path.join(relative_dir, module)
  618.                            for relative_dir in hardcoded_relative_dirs
  619.                            for module in ('plat-darwin', 'plat-mac', 'plat-mac/lib-scriptpackages')]
  620.  
  621.         for path in hardcoded_paths:
  622.             if os.path.exists(path):
  623.                 paths.append(path)
  624.  
  625.     sys.path.extend(paths)
  626.  
  627. def force_global_eggs_after_local_site_packages():
  628.     """
  629.    Force easy_installed eggs in the global environment to get placed
  630.    in sys.path after all packages inside the virtualenv.  This
  631.    maintains the "least surprise" result that packages in the
  632.    virtualenv always mask global packages, never the other way
  633.    around.
  634.  
  635.    """
  636.     egginsert = getattr(sys, '__egginsert', 0)
  637.     for i, path in enumerate(sys.path):
  638.         if i > egginsert and path.startswith(sys.prefix):
  639.             egginsert = i
  640.     sys.__egginsert = egginsert + 1
  641.  
  642. def virtual_addsitepackages(known_paths):
  643.     force_global_eggs_after_local_site_packages()
  644.     return addsitepackages(known_paths, sys_prefix=sys.real_prefix)
  645.  
  646. def fixclasspath():
  647.     """Adjust the special classpath sys.path entries for Jython. These
  648.    entries should follow the base virtualenv lib directories.
  649.    """
  650.     paths = []
  651.     classpaths = []
  652.     for path in sys.path:
  653.         if path == '__classpath__' or path.startswith('__pyclasspath__'):
  654.             classpaths.append(path)
  655.         else:
  656.             paths.append(path)
  657.     sys.path = paths
  658.     sys.path.extend(classpaths)
  659.  
  660. def execusercustomize():
  661.     """Run custom user specific code, if available."""
  662.     try:
  663.         import usercustomize
  664.     except ImportError:
  665.         pass
  666.  
  667.  
  668. def main():
  669.     global ENABLE_USER_SITE
  670.     virtual_install_main_packages()
  671.     abs__file__()
  672.     paths_in_sys = removeduppaths()
  673.     if (os.name == "posix" and sys.path and
  674.         os.path.basename(sys.path[-1]) == "Modules"):
  675.         addbuilddir()
  676.     if _is_jython:
  677.         fixclasspath()
  678.     GLOBAL_SITE_PACKAGES = not os.path.exists(os.path.join(os.path.dirname(__file__), 'no-global-site-packages.txt'))
  679.     if not GLOBAL_SITE_PACKAGES:
  680.         ENABLE_USER_SITE = False
  681.     if ENABLE_USER_SITE is None:
  682.         ENABLE_USER_SITE = check_enableusersite()
  683.     paths_in_sys = addsitepackages(paths_in_sys)
  684.     paths_in_sys = addusersitepackages(paths_in_sys)
  685.     if GLOBAL_SITE_PACKAGES:
  686.         paths_in_sys = virtual_addsitepackages(paths_in_sys)
  687.     if sys.platform == 'os2emx':
  688.         setBEGINLIBPATH()
  689.     setquit()
  690.     setcopyright()
  691.     sethelper()
  692.     aliasmbcs()
  693.     setencoding()
  694.     execsitecustomize()
  695.     if ENABLE_USER_SITE:
  696.         execusercustomize()
  697.     # Remove sys.setdefaultencoding() so that users cannot change the
  698.     # encoding after initialization.  The test for presence is needed when
  699.     # this module is run as a script, because this code is executed twice.
  700.     if hasattr(sys, "setdefaultencoding"):
  701.         del sys.setdefaultencoding
  702.  
  703. main()
  704.  
  705. def _script():
  706.     help = """\
  707.    %s [--user-base] [--user-site]
  708.  
  709.    Without arguments print some useful information
  710.    With arguments print the value of USER_BASE and/or USER_SITE separated
  711.    by '%s'.
  712.  
  713.    Exit codes with --user-base or --user-site:
  714.      0 - user site directory is enabled
  715.      1 - user site directory is disabled by user
  716.      2 - uses site directory is disabled by super user
  717.          or for security reasons
  718.     >2 - unknown error
  719.    """
  720.     args = sys.argv[1:]
  721.     if not args:
  722.         print("sys.path = [")
  723.         for dir in sys.path:
  724.             print("    %r," % (dir,))
  725.         print("]")
  726.         def exists(path):
  727.             if os.path.isdir(path):
  728.                 return "exists"
  729.             else:
  730.                 return "doesn't exist"
  731.         print("USER_BASE: %r (%s)" % (USER_BASE, exists(USER_BASE)))
  732.         print("USER_SITE: %r (%s)" % (USER_SITE, exists(USER_BASE)))
  733.         print("ENABLE_USER_SITE: %r" %  ENABLE_USER_SITE)
  734.         sys.exit(0)
  735.  
  736.     buffer = []
  737.     if '--user-base' in args:
  738.         buffer.append(USER_BASE)
  739.     if '--user-site' in args:
  740.         buffer.append(USER_SITE)
  741.  
  742.     if buffer:
  743.         print(os.pathsep.join(buffer))
  744.         if ENABLE_USER_SITE:
  745.             sys.exit(0)
  746.         elif ENABLE_USER_SITE is False:
  747.             sys.exit(1)
  748.         elif ENABLE_USER_SITE is None:
  749.             sys.exit(2)
  750.         else:
  751.             sys.exit(3)
  752.     else:
  753.         import textwrap
  754.         print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
  755.         sys.exit(10)
  756.  
  757. if __name__ == '__main__':
  758.     _script()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement