dotfiles

My personal shell configs and stuff
git clone git://git.alex.balgavy.eu/dotfiles.git
Log | Files | Refs | Submodules | README | LICENSE

site.py (29003B)


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