python/virtualenv/virtualenv_embedded/site.py

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/python/virtualenv/virtualenv_embedded/site.py	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,758 @@
     1.4 +"""Append module search paths for third-party packages to sys.path.
     1.5 +
     1.6 +****************************************************************
     1.7 +* This module is automatically imported during initialization. *
     1.8 +****************************************************************
     1.9 +
    1.10 +In earlier versions of Python (up to 1.5a3), scripts or modules that
    1.11 +needed to use site-specific modules would place ``import site''
    1.12 +somewhere near the top of their code.  Because of the automatic
    1.13 +import, this is no longer necessary (but code that does it still
    1.14 +works).
    1.15 +
    1.16 +This will append site-specific paths to the module search path.  On
    1.17 +Unix, it starts with sys.prefix and sys.exec_prefix (if different) and
    1.18 +appends lib/python<version>/site-packages as well as lib/site-python.
    1.19 +It also supports the Debian convention of
    1.20 +lib/python<version>/dist-packages.  On other platforms (mainly Mac and
    1.21 +Windows), it uses just sys.prefix (and sys.exec_prefix, if different,
    1.22 +but this is unlikely).  The resulting directories, if they exist, are
    1.23 +appended to sys.path, and also inspected for path configuration files.
    1.24 +
    1.25 +FOR DEBIAN, this sys.path is augmented with directories in /usr/local.
    1.26 +Local addons go into /usr/local/lib/python<version>/site-packages
    1.27 +(resp. /usr/local/lib/site-python), Debian addons install into
    1.28 +/usr/{lib,share}/python<version>/dist-packages.
    1.29 +
    1.30 +A path configuration file is a file whose name has the form
    1.31 +<package>.pth; its contents are additional directories (one per line)
    1.32 +to be added to sys.path.  Non-existing directories (or
    1.33 +non-directories) are never added to sys.path; no directory is added to
    1.34 +sys.path more than once.  Blank lines and lines beginning with
    1.35 +'#' are skipped. Lines starting with 'import' are executed.
    1.36 +
    1.37 +For example, suppose sys.prefix and sys.exec_prefix are set to
    1.38 +/usr/local and there is a directory /usr/local/lib/python2.X/site-packages
    1.39 +with three subdirectories, foo, bar and spam, and two path
    1.40 +configuration files, foo.pth and bar.pth.  Assume foo.pth contains the
    1.41 +following:
    1.42 +
    1.43 +  # foo package configuration
    1.44 +  foo
    1.45 +  bar
    1.46 +  bletch
    1.47 +
    1.48 +and bar.pth contains:
    1.49 +
    1.50 +  # bar package configuration
    1.51 +  bar
    1.52 +
    1.53 +Then the following directories are added to sys.path, in this order:
    1.54 +
    1.55 +  /usr/local/lib/python2.X/site-packages/bar
    1.56 +  /usr/local/lib/python2.X/site-packages/foo
    1.57 +
    1.58 +Note that bletch is omitted because it doesn't exist; bar precedes foo
    1.59 +because bar.pth comes alphabetically before foo.pth; and spam is
    1.60 +omitted because it is not mentioned in either path configuration file.
    1.61 +
    1.62 +After these path manipulations, an attempt is made to import a module
    1.63 +named sitecustomize, which can perform arbitrary additional
    1.64 +site-specific customizations.  If this import fails with an
    1.65 +ImportError exception, it is silently ignored.
    1.66 +
    1.67 +"""
    1.68 +
    1.69 +import sys
    1.70 +import os
    1.71 +try:
    1.72 +    import __builtin__ as builtins
    1.73 +except ImportError:
    1.74 +    import builtins
    1.75 +try:
    1.76 +    set
    1.77 +except NameError:
    1.78 +    from sets import Set as set
    1.79 +
    1.80 +# Prefixes for site-packages; add additional prefixes like /usr/local here
    1.81 +PREFIXES = [sys.prefix, sys.exec_prefix]
    1.82 +# Enable per user site-packages directory
    1.83 +# set it to False to disable the feature or True to force the feature
    1.84 +ENABLE_USER_SITE = None
    1.85 +# for distutils.commands.install
    1.86 +USER_SITE = None
    1.87 +USER_BASE = None
    1.88 +
    1.89 +_is_64bit = (getattr(sys, 'maxsize', None) or getattr(sys, 'maxint')) > 2**32
    1.90 +_is_pypy = hasattr(sys, 'pypy_version_info')
    1.91 +_is_jython = sys.platform[:4] == 'java'
    1.92 +if _is_jython:
    1.93 +    ModuleType = type(os)
    1.94 +
    1.95 +def makepath(*paths):
    1.96 +    dir = os.path.join(*paths)
    1.97 +    if _is_jython and (dir == '__classpath__' or
    1.98 +                       dir.startswith('__pyclasspath__')):
    1.99 +        return dir, dir
   1.100 +    dir = os.path.abspath(dir)
   1.101 +    return dir, os.path.normcase(dir)
   1.102 +
   1.103 +def abs__file__():
   1.104 +    """Set all module' __file__ attribute to an absolute path"""
   1.105 +    for m in sys.modules.values():
   1.106 +        if ((_is_jython and not isinstance(m, ModuleType)) or
   1.107 +            hasattr(m, '__loader__')):
   1.108 +            # only modules need the abspath in Jython. and don't mess
   1.109 +            # with a PEP 302-supplied __file__
   1.110 +            continue
   1.111 +        f = getattr(m, '__file__', None)
   1.112 +        if f is None:
   1.113 +            continue
   1.114 +        m.__file__ = os.path.abspath(f)
   1.115 +
   1.116 +def removeduppaths():
   1.117 +    """ Remove duplicate entries from sys.path along with making them
   1.118 +    absolute"""
   1.119 +    # This ensures that the initial path provided by the interpreter contains
   1.120 +    # only absolute pathnames, even if we're running from the build directory.
   1.121 +    L = []
   1.122 +    known_paths = set()
   1.123 +    for dir in sys.path:
   1.124 +        # Filter out duplicate paths (on case-insensitive file systems also
   1.125 +        # if they only differ in case); turn relative paths into absolute
   1.126 +        # paths.
   1.127 +        dir, dircase = makepath(dir)
   1.128 +        if not dircase in known_paths:
   1.129 +            L.append(dir)
   1.130 +            known_paths.add(dircase)
   1.131 +    sys.path[:] = L
   1.132 +    return known_paths
   1.133 +
   1.134 +# XXX This should not be part of site.py, since it is needed even when
   1.135 +# using the -S option for Python.  See http://www.python.org/sf/586680
   1.136 +def addbuilddir():
   1.137 +    """Append ./build/lib.<platform> in case we're running in the build dir
   1.138 +    (especially for Guido :-)"""
   1.139 +    from distutils.util import get_platform
   1.140 +    s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
   1.141 +    if hasattr(sys, 'gettotalrefcount'):
   1.142 +        s += '-pydebug'
   1.143 +    s = os.path.join(os.path.dirname(sys.path[-1]), s)
   1.144 +    sys.path.append(s)
   1.145 +
   1.146 +def _init_pathinfo():
   1.147 +    """Return a set containing all existing directory entries from sys.path"""
   1.148 +    d = set()
   1.149 +    for dir in sys.path:
   1.150 +        try:
   1.151 +            if os.path.isdir(dir):
   1.152 +                dir, dircase = makepath(dir)
   1.153 +                d.add(dircase)
   1.154 +        except TypeError:
   1.155 +            continue
   1.156 +    return d
   1.157 +
   1.158 +def addpackage(sitedir, name, known_paths):
   1.159 +    """Add a new path to known_paths by combining sitedir and 'name' or execute
   1.160 +    sitedir if it starts with 'import'"""
   1.161 +    if known_paths is None:
   1.162 +        _init_pathinfo()
   1.163 +        reset = 1
   1.164 +    else:
   1.165 +        reset = 0
   1.166 +    fullname = os.path.join(sitedir, name)
   1.167 +    try:
   1.168 +        f = open(fullname, "rU")
   1.169 +    except IOError:
   1.170 +        return
   1.171 +    try:
   1.172 +        for line in f:
   1.173 +            if line.startswith("#"):
   1.174 +                continue
   1.175 +            if line.startswith("import"):
   1.176 +                exec(line)
   1.177 +                continue
   1.178 +            line = line.rstrip()
   1.179 +            dir, dircase = makepath(sitedir, line)
   1.180 +            if not dircase in known_paths and os.path.exists(dir):
   1.181 +                sys.path.append(dir)
   1.182 +                known_paths.add(dircase)
   1.183 +    finally:
   1.184 +        f.close()
   1.185 +    if reset:
   1.186 +        known_paths = None
   1.187 +    return known_paths
   1.188 +
   1.189 +def addsitedir(sitedir, known_paths=None):
   1.190 +    """Add 'sitedir' argument to sys.path if missing and handle .pth files in
   1.191 +    'sitedir'"""
   1.192 +    if known_paths is None:
   1.193 +        known_paths = _init_pathinfo()
   1.194 +        reset = 1
   1.195 +    else:
   1.196 +        reset = 0
   1.197 +    sitedir, sitedircase = makepath(sitedir)
   1.198 +    if not sitedircase in known_paths:
   1.199 +        sys.path.append(sitedir)        # Add path component
   1.200 +    try:
   1.201 +        names = os.listdir(sitedir)
   1.202 +    except os.error:
   1.203 +        return
   1.204 +    names.sort()
   1.205 +    for name in names:
   1.206 +        if name.endswith(os.extsep + "pth"):
   1.207 +            addpackage(sitedir, name, known_paths)
   1.208 +    if reset:
   1.209 +        known_paths = None
   1.210 +    return known_paths
   1.211 +
   1.212 +def addsitepackages(known_paths, sys_prefix=sys.prefix, exec_prefix=sys.exec_prefix):
   1.213 +    """Add site-packages (and possibly site-python) to sys.path"""
   1.214 +    prefixes = [os.path.join(sys_prefix, "local"), sys_prefix]
   1.215 +    if exec_prefix != sys_prefix:
   1.216 +        prefixes.append(os.path.join(exec_prefix, "local"))
   1.217 +
   1.218 +    for prefix in prefixes:
   1.219 +        if prefix:
   1.220 +            if sys.platform in ('os2emx', 'riscos') or _is_jython:
   1.221 +                sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
   1.222 +            elif _is_pypy:
   1.223 +                sitedirs = [os.path.join(prefix, 'site-packages')]
   1.224 +            elif sys.platform == 'darwin' and prefix == sys_prefix:
   1.225 +
   1.226 +                if prefix.startswith("/System/Library/Frameworks/"): # Apple's Python
   1.227 +
   1.228 +                    sitedirs = [os.path.join("/Library/Python", sys.version[:3], "site-packages"),
   1.229 +                                os.path.join(prefix, "Extras", "lib", "python")]
   1.230 +
   1.231 +                else: # any other Python distros on OSX work this way
   1.232 +                    sitedirs = [os.path.join(prefix, "lib",
   1.233 +                                             "python" + sys.version[:3], "site-packages")]
   1.234 +
   1.235 +            elif os.sep == '/':
   1.236 +                sitedirs = [os.path.join(prefix,
   1.237 +                                         "lib",
   1.238 +                                         "python" + sys.version[:3],
   1.239 +                                         "site-packages"),
   1.240 +                            os.path.join(prefix, "lib", "site-python"),
   1.241 +                            os.path.join(prefix, "python" + sys.version[:3], "lib-dynload")]
   1.242 +                lib64_dir = os.path.join(prefix, "lib64", "python" + sys.version[:3], "site-packages")
   1.243 +                if (os.path.exists(lib64_dir) and
   1.244 +                    os.path.realpath(lib64_dir) not in [os.path.realpath(p) for p in sitedirs]):
   1.245 +                    if _is_64bit:
   1.246 +                        sitedirs.insert(0, lib64_dir)
   1.247 +                    else:
   1.248 +                        sitedirs.append(lib64_dir)
   1.249 +                try:
   1.250 +                    # sys.getobjects only available in --with-pydebug build
   1.251 +                    sys.getobjects
   1.252 +                    sitedirs.insert(0, os.path.join(sitedirs[0], 'debug'))
   1.253 +                except AttributeError:
   1.254 +                    pass
   1.255 +                # Debian-specific dist-packages directories:
   1.256 +                if sys.version[0] == '2':
   1.257 +                    sitedirs.append(os.path.join(prefix, "lib",
   1.258 +                                                 "python" + sys.version[:3],
   1.259 +                                                 "dist-packages"))
   1.260 +                else:
   1.261 +                    sitedirs.append(os.path.join(prefix, "lib",
   1.262 +                                                 "python" + sys.version[0],
   1.263 +                                                 "dist-packages"))
   1.264 +                sitedirs.append(os.path.join(prefix, "local/lib",
   1.265 +                                             "python" + sys.version[:3],
   1.266 +                                             "dist-packages"))
   1.267 +                sitedirs.append(os.path.join(prefix, "lib", "dist-python"))
   1.268 +            else:
   1.269 +                sitedirs = [prefix, os.path.join(prefix, "lib", "site-packages")]
   1.270 +            if sys.platform == 'darwin':
   1.271 +                # for framework builds *only* we add the standard Apple
   1.272 +                # locations. Currently only per-user, but /Library and
   1.273 +                # /Network/Library could be added too
   1.274 +                if 'Python.framework' in prefix:
   1.275 +                    home = os.environ.get('HOME')
   1.276 +                    if home:
   1.277 +                        sitedirs.append(
   1.278 +                            os.path.join(home,
   1.279 +                                         'Library',
   1.280 +                                         'Python',
   1.281 +                                         sys.version[:3],
   1.282 +                                         'site-packages'))
   1.283 +            for sitedir in sitedirs:
   1.284 +                if os.path.isdir(sitedir):
   1.285 +                    addsitedir(sitedir, known_paths)
   1.286 +    return None
   1.287 +
   1.288 +def check_enableusersite():
   1.289 +    """Check if user site directory is safe for inclusion
   1.290 +
   1.291 +    The function tests for the command line flag (including environment var),
   1.292 +    process uid/gid equal to effective uid/gid.
   1.293 +
   1.294 +    None: Disabled for security reasons
   1.295 +    False: Disabled by user (command line option)
   1.296 +    True: Safe and enabled
   1.297 +    """
   1.298 +    if hasattr(sys, 'flags') and getattr(sys.flags, 'no_user_site', False):
   1.299 +        return False
   1.300 +
   1.301 +    if hasattr(os, "getuid") and hasattr(os, "geteuid"):
   1.302 +        # check process uid == effective uid
   1.303 +        if os.geteuid() != os.getuid():
   1.304 +            return None
   1.305 +    if hasattr(os, "getgid") and hasattr(os, "getegid"):
   1.306 +        # check process gid == effective gid
   1.307 +        if os.getegid() != os.getgid():
   1.308 +            return None
   1.309 +
   1.310 +    return True
   1.311 +
   1.312 +def addusersitepackages(known_paths):
   1.313 +    """Add a per user site-package to sys.path
   1.314 +
   1.315 +    Each user has its own python directory with site-packages in the
   1.316 +    home directory.
   1.317 +
   1.318 +    USER_BASE is the root directory for all Python versions
   1.319 +
   1.320 +    USER_SITE is the user specific site-packages directory
   1.321 +
   1.322 +    USER_SITE/.. can be used for data.
   1.323 +    """
   1.324 +    global USER_BASE, USER_SITE, ENABLE_USER_SITE
   1.325 +    env_base = os.environ.get("PYTHONUSERBASE", None)
   1.326 +
   1.327 +    def joinuser(*args):
   1.328 +        return os.path.expanduser(os.path.join(*args))
   1.329 +
   1.330 +    #if sys.platform in ('os2emx', 'riscos'):
   1.331 +    #    # Don't know what to put here
   1.332 +    #    USER_BASE = ''
   1.333 +    #    USER_SITE = ''
   1.334 +    if os.name == "nt":
   1.335 +        base = os.environ.get("APPDATA") or "~"
   1.336 +        if env_base:
   1.337 +            USER_BASE = env_base
   1.338 +        else:
   1.339 +            USER_BASE = joinuser(base, "Python")
   1.340 +        USER_SITE = os.path.join(USER_BASE,
   1.341 +                                 "Python" + sys.version[0] + sys.version[2],
   1.342 +                                 "site-packages")
   1.343 +    else:
   1.344 +        if env_base:
   1.345 +            USER_BASE = env_base
   1.346 +        else:
   1.347 +            USER_BASE = joinuser("~", ".local")
   1.348 +        USER_SITE = os.path.join(USER_BASE, "lib",
   1.349 +                                 "python" + sys.version[:3],
   1.350 +                                 "site-packages")
   1.351 +
   1.352 +    if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
   1.353 +        addsitedir(USER_SITE, known_paths)
   1.354 +    if ENABLE_USER_SITE:
   1.355 +        for dist_libdir in ("lib", "local/lib"):
   1.356 +            user_site = os.path.join(USER_BASE, dist_libdir,
   1.357 +                                     "python" + sys.version[:3],
   1.358 +                                     "dist-packages")
   1.359 +            if os.path.isdir(user_site):
   1.360 +                addsitedir(user_site, known_paths)
   1.361 +    return known_paths
   1.362 +
   1.363 +
   1.364 +
   1.365 +def setBEGINLIBPATH():
   1.366 +    """The OS/2 EMX port has optional extension modules that do double duty
   1.367 +    as DLLs (and must use the .DLL file extension) for other extensions.
   1.368 +    The library search path needs to be amended so these will be found
   1.369 +    during module import.  Use BEGINLIBPATH so that these are at the start
   1.370 +    of the library search path.
   1.371 +
   1.372 +    """
   1.373 +    dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
   1.374 +    libpath = os.environ['BEGINLIBPATH'].split(';')
   1.375 +    if libpath[-1]:
   1.376 +        libpath.append(dllpath)
   1.377 +    else:
   1.378 +        libpath[-1] = dllpath
   1.379 +    os.environ['BEGINLIBPATH'] = ';'.join(libpath)
   1.380 +
   1.381 +
   1.382 +def setquit():
   1.383 +    """Define new built-ins 'quit' and 'exit'.
   1.384 +    These are simply strings that display a hint on how to exit.
   1.385 +
   1.386 +    """
   1.387 +    if os.sep == ':':
   1.388 +        eof = 'Cmd-Q'
   1.389 +    elif os.sep == '\\':
   1.390 +        eof = 'Ctrl-Z plus Return'
   1.391 +    else:
   1.392 +        eof = 'Ctrl-D (i.e. EOF)'
   1.393 +
   1.394 +    class Quitter(object):
   1.395 +        def __init__(self, name):
   1.396 +            self.name = name
   1.397 +        def __repr__(self):
   1.398 +            return 'Use %s() or %s to exit' % (self.name, eof)
   1.399 +        def __call__(self, code=None):
   1.400 +            # Shells like IDLE catch the SystemExit, but listen when their
   1.401 +            # stdin wrapper is closed.
   1.402 +            try:
   1.403 +                sys.stdin.close()
   1.404 +            except:
   1.405 +                pass
   1.406 +            raise SystemExit(code)
   1.407 +    builtins.quit = Quitter('quit')
   1.408 +    builtins.exit = Quitter('exit')
   1.409 +
   1.410 +
   1.411 +class _Printer(object):
   1.412 +    """interactive prompt objects for printing the license text, a list of
   1.413 +    contributors and the copyright notice."""
   1.414 +
   1.415 +    MAXLINES = 23
   1.416 +
   1.417 +    def __init__(self, name, data, files=(), dirs=()):
   1.418 +        self.__name = name
   1.419 +        self.__data = data
   1.420 +        self.__files = files
   1.421 +        self.__dirs = dirs
   1.422 +        self.__lines = None
   1.423 +
   1.424 +    def __setup(self):
   1.425 +        if self.__lines:
   1.426 +            return
   1.427 +        data = None
   1.428 +        for dir in self.__dirs:
   1.429 +            for filename in self.__files:
   1.430 +                filename = os.path.join(dir, filename)
   1.431 +                try:
   1.432 +                    fp = open(filename, "rU")
   1.433 +                    data = fp.read()
   1.434 +                    fp.close()
   1.435 +                    break
   1.436 +                except IOError:
   1.437 +                    pass
   1.438 +            if data:
   1.439 +                break
   1.440 +        if not data:
   1.441 +            data = self.__data
   1.442 +        self.__lines = data.split('\n')
   1.443 +        self.__linecnt = len(self.__lines)
   1.444 +
   1.445 +    def __repr__(self):
   1.446 +        self.__setup()
   1.447 +        if len(self.__lines) <= self.MAXLINES:
   1.448 +            return "\n".join(self.__lines)
   1.449 +        else:
   1.450 +            return "Type %s() to see the full %s text" % ((self.__name,)*2)
   1.451 +
   1.452 +    def __call__(self):
   1.453 +        self.__setup()
   1.454 +        prompt = 'Hit Return for more, or q (and Return) to quit: '
   1.455 +        lineno = 0
   1.456 +        while 1:
   1.457 +            try:
   1.458 +                for i in range(lineno, lineno + self.MAXLINES):
   1.459 +                    print(self.__lines[i])
   1.460 +            except IndexError:
   1.461 +                break
   1.462 +            else:
   1.463 +                lineno += self.MAXLINES
   1.464 +                key = None
   1.465 +                while key is None:
   1.466 +                    try:
   1.467 +                        key = raw_input(prompt)
   1.468 +                    except NameError:
   1.469 +                        key = input(prompt)
   1.470 +                    if key not in ('', 'q'):
   1.471 +                        key = None
   1.472 +                if key == 'q':
   1.473 +                    break
   1.474 +
   1.475 +def setcopyright():
   1.476 +    """Set 'copyright' and 'credits' in __builtin__"""
   1.477 +    builtins.copyright = _Printer("copyright", sys.copyright)
   1.478 +    if _is_jython:
   1.479 +        builtins.credits = _Printer(
   1.480 +            "credits",
   1.481 +            "Jython is maintained by the Jython developers (www.jython.org).")
   1.482 +    elif _is_pypy:
   1.483 +        builtins.credits = _Printer(
   1.484 +            "credits",
   1.485 +            "PyPy is maintained by the PyPy developers: http://pypy.org/")
   1.486 +    else:
   1.487 +        builtins.credits = _Printer("credits", """\
   1.488 +    Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
   1.489 +    for supporting Python development.  See www.python.org for more information.""")
   1.490 +    here = os.path.dirname(os.__file__)
   1.491 +    builtins.license = _Printer(
   1.492 +        "license", "See http://www.python.org/%.3s/license.html" % sys.version,
   1.493 +        ["LICENSE.txt", "LICENSE"],
   1.494 +        [os.path.join(here, os.pardir), here, os.curdir])
   1.495 +
   1.496 +
   1.497 +class _Helper(object):
   1.498 +    """Define the built-in 'help'.
   1.499 +    This is a wrapper around pydoc.help (with a twist).
   1.500 +
   1.501 +    """
   1.502 +
   1.503 +    def __repr__(self):
   1.504 +        return "Type help() for interactive help, " \
   1.505 +               "or help(object) for help about object."
   1.506 +    def __call__(self, *args, **kwds):
   1.507 +        import pydoc
   1.508 +        return pydoc.help(*args, **kwds)
   1.509 +
   1.510 +def sethelper():
   1.511 +    builtins.help = _Helper()
   1.512 +
   1.513 +def aliasmbcs():
   1.514 +    """On Windows, some default encodings are not provided by Python,
   1.515 +    while they are always available as "mbcs" in each locale. Make
   1.516 +    them usable by aliasing to "mbcs" in such a case."""
   1.517 +    if sys.platform == 'win32':
   1.518 +        import locale, codecs
   1.519 +        enc = locale.getdefaultlocale()[1]
   1.520 +        if enc.startswith('cp'):            # "cp***" ?
   1.521 +            try:
   1.522 +                codecs.lookup(enc)
   1.523 +            except LookupError:
   1.524 +                import encodings
   1.525 +                encodings._cache[enc] = encodings._unknown
   1.526 +                encodings.aliases.aliases[enc] = 'mbcs'
   1.527 +
   1.528 +def setencoding():
   1.529 +    """Set the string encoding used by the Unicode implementation.  The
   1.530 +    default is 'ascii', but if you're willing to experiment, you can
   1.531 +    change this."""
   1.532 +    encoding = "ascii" # Default value set by _PyUnicode_Init()
   1.533 +    if 0:
   1.534 +        # Enable to support locale aware default string encodings.
   1.535 +        import locale
   1.536 +        loc = locale.getdefaultlocale()
   1.537 +        if loc[1]:
   1.538 +            encoding = loc[1]
   1.539 +    if 0:
   1.540 +        # Enable to switch off string to Unicode coercion and implicit
   1.541 +        # Unicode to string conversion.
   1.542 +        encoding = "undefined"
   1.543 +    if encoding != "ascii":
   1.544 +        # On Non-Unicode builds this will raise an AttributeError...
   1.545 +        sys.setdefaultencoding(encoding) # Needs Python Unicode build !
   1.546 +
   1.547 +
   1.548 +def execsitecustomize():
   1.549 +    """Run custom site specific code, if available."""
   1.550 +    try:
   1.551 +        import sitecustomize
   1.552 +    except ImportError:
   1.553 +        pass
   1.554 +
   1.555 +def virtual_install_main_packages():
   1.556 +    f = open(os.path.join(os.path.dirname(__file__), 'orig-prefix.txt'))
   1.557 +    sys.real_prefix = f.read().strip()
   1.558 +    f.close()
   1.559 +    pos = 2
   1.560 +    hardcoded_relative_dirs = []
   1.561 +    if sys.path[0] == '':
   1.562 +        pos += 1
   1.563 +    if _is_jython:
   1.564 +        paths = [os.path.join(sys.real_prefix, 'Lib')]
   1.565 +    elif _is_pypy:
   1.566 +        if sys.version_info > (3, 2):
   1.567 +            cpyver = '%d' % sys.version_info[0]
   1.568 +        elif sys.pypy_version_info >= (1, 5):
   1.569 +            cpyver = '%d.%d' % sys.version_info[:2]
   1.570 +        else:
   1.571 +            cpyver = '%d.%d.%d' % sys.version_info[:3]
   1.572 +        paths = [os.path.join(sys.real_prefix, 'lib_pypy'),
   1.573 +                 os.path.join(sys.real_prefix, 'lib-python', cpyver)]
   1.574 +        if sys.pypy_version_info < (1, 9):
   1.575 +            paths.insert(1, os.path.join(sys.real_prefix,
   1.576 +                                         'lib-python', 'modified-%s' % cpyver))
   1.577 +        hardcoded_relative_dirs = paths[:] # for the special 'darwin' case below
   1.578 +        #
   1.579 +        # This is hardcoded in the Python executable, but relative to sys.prefix:
   1.580 +        for path in paths[:]:
   1.581 +            plat_path = os.path.join(path, 'plat-%s' % sys.platform)
   1.582 +            if os.path.exists(plat_path):
   1.583 +                paths.append(plat_path)
   1.584 +    elif sys.platform == 'win32':
   1.585 +        paths = [os.path.join(sys.real_prefix, 'Lib'), os.path.join(sys.real_prefix, 'DLLs')]
   1.586 +    else:
   1.587 +        paths = [os.path.join(sys.real_prefix, 'lib', 'python'+sys.version[:3])]
   1.588 +        hardcoded_relative_dirs = paths[:] # for the special 'darwin' case below
   1.589 +        lib64_path = os.path.join(sys.real_prefix, 'lib64', 'python'+sys.version[:3])
   1.590 +        if os.path.exists(lib64_path):
   1.591 +            if _is_64bit:
   1.592 +                paths.insert(0, lib64_path)
   1.593 +            else:
   1.594 +                paths.append(lib64_path)
   1.595 +        # This is hardcoded in the Python executable, but relative to
   1.596 +        # sys.prefix.  Debian change: we need to add the multiarch triplet
   1.597 +        # here, which is where the real stuff lives.  As per PEP 421, in
   1.598 +        # Python 3.3+, this lives in sys.implementation, while in Python 2.7
   1.599 +        # it lives in sys.
   1.600 +        try:
   1.601 +            arch = getattr(sys, 'implementation', sys)._multiarch
   1.602 +        except AttributeError:
   1.603 +            # This is a non-multiarch aware Python.  Fallback to the old way.
   1.604 +            arch = sys.platform
   1.605 +        plat_path = os.path.join(sys.real_prefix, 'lib',
   1.606 +                                 'python'+sys.version[:3],
   1.607 +                                 'plat-%s' % arch)
   1.608 +        if os.path.exists(plat_path):
   1.609 +            paths.append(plat_path)
   1.610 +    # This is hardcoded in the Python executable, but
   1.611 +    # relative to sys.prefix, so we have to fix up:
   1.612 +    for path in list(paths):
   1.613 +        tk_dir = os.path.join(path, 'lib-tk')
   1.614 +        if os.path.exists(tk_dir):
   1.615 +            paths.append(tk_dir)
   1.616 +
   1.617 +    # These are hardcoded in the Apple's Python executable,
   1.618 +    # but relative to sys.prefix, so we have to fix them up:
   1.619 +    if sys.platform == 'darwin':
   1.620 +        hardcoded_paths = [os.path.join(relative_dir, module)
   1.621 +                           for relative_dir in hardcoded_relative_dirs
   1.622 +                           for module in ('plat-darwin', 'plat-mac', 'plat-mac/lib-scriptpackages')]
   1.623 +
   1.624 +        for path in hardcoded_paths:
   1.625 +            if os.path.exists(path):
   1.626 +                paths.append(path)
   1.627 +
   1.628 +    sys.path.extend(paths)
   1.629 +
   1.630 +def force_global_eggs_after_local_site_packages():
   1.631 +    """
   1.632 +    Force easy_installed eggs in the global environment to get placed
   1.633 +    in sys.path after all packages inside the virtualenv.  This
   1.634 +    maintains the "least surprise" result that packages in the
   1.635 +    virtualenv always mask global packages, never the other way
   1.636 +    around.
   1.637 +
   1.638 +    """
   1.639 +    egginsert = getattr(sys, '__egginsert', 0)
   1.640 +    for i, path in enumerate(sys.path):
   1.641 +        if i > egginsert and path.startswith(sys.prefix):
   1.642 +            egginsert = i
   1.643 +    sys.__egginsert = egginsert + 1
   1.644 +
   1.645 +def virtual_addsitepackages(known_paths):
   1.646 +    force_global_eggs_after_local_site_packages()
   1.647 +    return addsitepackages(known_paths, sys_prefix=sys.real_prefix)
   1.648 +
   1.649 +def fixclasspath():
   1.650 +    """Adjust the special classpath sys.path entries for Jython. These
   1.651 +    entries should follow the base virtualenv lib directories.
   1.652 +    """
   1.653 +    paths = []
   1.654 +    classpaths = []
   1.655 +    for path in sys.path:
   1.656 +        if path == '__classpath__' or path.startswith('__pyclasspath__'):
   1.657 +            classpaths.append(path)
   1.658 +        else:
   1.659 +            paths.append(path)
   1.660 +    sys.path = paths
   1.661 +    sys.path.extend(classpaths)
   1.662 +
   1.663 +def execusercustomize():
   1.664 +    """Run custom user specific code, if available."""
   1.665 +    try:
   1.666 +        import usercustomize
   1.667 +    except ImportError:
   1.668 +        pass
   1.669 +
   1.670 +
   1.671 +def main():
   1.672 +    global ENABLE_USER_SITE
   1.673 +    virtual_install_main_packages()
   1.674 +    abs__file__()
   1.675 +    paths_in_sys = removeduppaths()
   1.676 +    if (os.name == "posix" and sys.path and
   1.677 +        os.path.basename(sys.path[-1]) == "Modules"):
   1.678 +        addbuilddir()
   1.679 +    if _is_jython:
   1.680 +        fixclasspath()
   1.681 +    GLOBAL_SITE_PACKAGES = not os.path.exists(os.path.join(os.path.dirname(__file__), 'no-global-site-packages.txt'))
   1.682 +    if not GLOBAL_SITE_PACKAGES:
   1.683 +        ENABLE_USER_SITE = False
   1.684 +    if ENABLE_USER_SITE is None:
   1.685 +        ENABLE_USER_SITE = check_enableusersite()
   1.686 +    paths_in_sys = addsitepackages(paths_in_sys)
   1.687 +    paths_in_sys = addusersitepackages(paths_in_sys)
   1.688 +    if GLOBAL_SITE_PACKAGES:
   1.689 +        paths_in_sys = virtual_addsitepackages(paths_in_sys)
   1.690 +    if sys.platform == 'os2emx':
   1.691 +        setBEGINLIBPATH()
   1.692 +    setquit()
   1.693 +    setcopyright()
   1.694 +    sethelper()
   1.695 +    aliasmbcs()
   1.696 +    setencoding()
   1.697 +    execsitecustomize()
   1.698 +    if ENABLE_USER_SITE:
   1.699 +        execusercustomize()
   1.700 +    # Remove sys.setdefaultencoding() so that users cannot change the
   1.701 +    # encoding after initialization.  The test for presence is needed when
   1.702 +    # this module is run as a script, because this code is executed twice.
   1.703 +    if hasattr(sys, "setdefaultencoding"):
   1.704 +        del sys.setdefaultencoding
   1.705 +
   1.706 +main()
   1.707 +
   1.708 +def _script():
   1.709 +    help = """\
   1.710 +    %s [--user-base] [--user-site]
   1.711 +
   1.712 +    Without arguments print some useful information
   1.713 +    With arguments print the value of USER_BASE and/or USER_SITE separated
   1.714 +    by '%s'.
   1.715 +
   1.716 +    Exit codes with --user-base or --user-site:
   1.717 +      0 - user site directory is enabled
   1.718 +      1 - user site directory is disabled by user
   1.719 +      2 - uses site directory is disabled by super user
   1.720 +          or for security reasons
   1.721 +     >2 - unknown error
   1.722 +    """
   1.723 +    args = sys.argv[1:]
   1.724 +    if not args:
   1.725 +        print("sys.path = [")
   1.726 +        for dir in sys.path:
   1.727 +            print("    %r," % (dir,))
   1.728 +        print("]")
   1.729 +        def exists(path):
   1.730 +            if os.path.isdir(path):
   1.731 +                return "exists"
   1.732 +            else:
   1.733 +                return "doesn't exist"
   1.734 +        print("USER_BASE: %r (%s)" % (USER_BASE, exists(USER_BASE)))
   1.735 +        print("USER_SITE: %r (%s)" % (USER_SITE, exists(USER_BASE)))
   1.736 +        print("ENABLE_USER_SITE: %r" %  ENABLE_USER_SITE)
   1.737 +        sys.exit(0)
   1.738 +
   1.739 +    buffer = []
   1.740 +    if '--user-base' in args:
   1.741 +        buffer.append(USER_BASE)
   1.742 +    if '--user-site' in args:
   1.743 +        buffer.append(USER_SITE)
   1.744 +
   1.745 +    if buffer:
   1.746 +        print(os.pathsep.join(buffer))
   1.747 +        if ENABLE_USER_SITE:
   1.748 +            sys.exit(0)
   1.749 +        elif ENABLE_USER_SITE is False:
   1.750 +            sys.exit(1)
   1.751 +        elif ENABLE_USER_SITE is None:
   1.752 +            sys.exit(2)
   1.753 +        else:
   1.754 +            sys.exit(3)
   1.755 +    else:
   1.756 +        import textwrap
   1.757 +        print(textwrap.dedent(help % (sys.argv[0], os.pathsep)))
   1.758 +        sys.exit(10)
   1.759 +
   1.760 +if __name__ == '__main__':
   1.761 +    _script()

mercurial