Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Lib/site.py

    r383 r391  
    6262import os
    6363import __builtin__
     64import traceback
    6465
    6566# Prefixes for site-packages; add additional prefixes like /usr/local here
     
    6869# set it to False to disable the feature or True to force the feature
    6970ENABLE_USER_SITE = None
     71
    7072# for distutils.commands.install
     73# These values are initialized by the getuserbase() and getusersitepackages()
     74# functions, through the main() function when Python starts.
    7175USER_SITE = None
    7276USER_BASE = None
     
    7478
    7579def makepath(*paths):
    76     dir = os.path.abspath(os.path.join(*paths))
     80    dir = os.path.join(*paths)
     81    try:
     82        dir = os.path.abspath(dir)
     83    except OSError:
     84        pass
    7785    return dir, os.path.normcase(dir)
    7886
     
    8593        try:
    8694            m.__file__ = os.path.abspath(m.__file__)
    87         except AttributeError:
    88             continue
     95        except (AttributeError, OSError):
     96            pass
    8997
    9098
     
    107115    return known_paths
    108116
    109 # XXX This should not be part of site.py, since it is needed even when
    110 # using the -S option for Python.  See http://www.python.org/sf/586680
    111 def addbuilddir():
    112     """Append ./build/lib.<platform> in case we're running in the build dir
    113     (especially for Guido :-)"""
    114     from distutils.util import get_platform
    115     s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
    116     if hasattr(sys, 'gettotalrefcount'):
    117         s += '-pydebug'
    118     s = os.path.join(os.path.dirname(sys.path[-1]), s)
    119     sys.path.append(s)
    120 
    121117
    122118def _init_pathinfo():
     
    149145        return
    150146    with f:
    151         for line in f:
     147        for n, line in enumerate(f):
    152148            if line.startswith("#"):
    153149                continue
    154             if line.startswith(("import ", "import\t")):
    155                 exec line
    156                 continue
    157             line = line.rstrip()
    158             dir, dircase = makepath(sitedir, line)
    159             if not dircase in known_paths and os.path.exists(dir):
    160                 sys.path.append(dir)
    161                 known_paths.add(dircase)
     150            try:
     151                if line.startswith(("import ", "import\t")):
     152                    exec line
     153                    continue
     154                line = line.rstrip()
     155                dir, dircase = makepath(sitedir, line)
     156                if not dircase in known_paths and os.path.exists(dir):
     157                    sys.path.append(dir)
     158                    known_paths.add(dircase)
     159            except Exception as err:
     160                print >>sys.stderr, "Error processing line {:d} of {}:\n".format(
     161                    n+1, fullname)
     162                for record in traceback.format_exception(*sys.exc_info()):
     163                    for line in record.splitlines():
     164                        print >>sys.stderr, '  '+line
     165                print >>sys.stderr, "\nRemainder of file ignored"
     166                break
    162167    if reset:
    163168        known_paths = None
     
    213218    return True
    214219
     220def getuserbase():
     221    """Returns the `user base` directory path.
     222
     223    The `user base` directory can be used to store data. If the global
     224    variable ``USER_BASE`` is not initialized yet, this function will also set
     225    it.
     226    """
     227    global USER_BASE
     228    if USER_BASE is not None:
     229        return USER_BASE
     230    from sysconfig import get_config_var
     231    USER_BASE = get_config_var('userbase')
     232    return USER_BASE
     233
     234def getusersitepackages():
     235    """Returns the user-specific site-packages directory path.
     236
     237    If the global variable ``USER_SITE`` is not initialized yet, this
     238    function will also set it.
     239    """
     240    global USER_SITE
     241    user_base = getuserbase() # this will also set USER_BASE
     242
     243    if USER_SITE is not None:
     244        return USER_SITE
     245
     246    from sysconfig import get_path
     247    import os
     248
     249    if sys.platform == 'darwin':
     250        from sysconfig import get_config_var
     251        if get_config_var('PYTHONFRAMEWORK'):
     252            USER_SITE = get_path('purelib', 'osx_framework_user')
     253            return USER_SITE
     254
     255    USER_SITE = get_path('purelib', '%s_user' % os.name)
     256    return USER_SITE
    215257
    216258def addusersitepackages(known_paths):
     
    219261    Each user has its own python directory with site-packages in the
    220262    home directory.
    221 
    222     USER_BASE is the root directory for all Python versions
    223 
    224     USER_SITE is the user specific site-packages directory
    225 
    226     USER_SITE/.. can be used for data.
    227     """
    228     global USER_BASE, USER_SITE, ENABLE_USER_SITE
    229     env_base = os.environ.get("PYTHONUSERBASE", None)
    230 
    231     def joinuser(*args):
    232         return os.path.expanduser(os.path.join(*args))
    233 
    234     #if sys.platform in ('os2emx', 'os2knix', 'riscos'):
    235     #    # Don't know what to put here
    236     #    USER_BASE = ''
    237     #    USER_SITE = ''
    238     if os.name == "nt":
    239         base = os.environ.get("APPDATA") or "~"
    240         USER_BASE = env_base if env_base else joinuser(base, "Python")
    241         USER_SITE = os.path.join(USER_BASE,
    242                                  "Python" + sys.version[0] + sys.version[2],
    243                                  "site-packages")
    244     else:
    245         USER_BASE = env_base if env_base else joinuser("~", ".local")
    246         USER_SITE = os.path.join(USER_BASE, "lib",
    247                                  "python" + sys.version[:3],
    248                                  "site-packages")
    249 
    250     if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
    251         addsitedir(USER_SITE, known_paths)
     263    """
     264    # get the per user site-package path
     265    # this call will also make sure USER_BASE and USER_SITE are set
     266    user_site = getusersitepackages()
     267
     268    if ENABLE_USER_SITE and os.path.isdir(user_site):
     269        addsitedir(user_site, known_paths)
    252270    return known_paths
    253271
    254 
    255 def addsitepackages(known_paths):
    256     """Add site-packages (and possibly site-python) to sys.path"""
    257     sitedirs = []
    258     seen = []
     272def getsitepackages():
     273    """Returns a list containing all global site-packages directories
     274    (and possibly site-python).
     275
     276    For each directory present in the global ``PREFIXES``, this function
     277    will find its `site-packages` subdirectory depending on the system
     278    environment, and will return a list of full paths.
     279    """
     280    sitepackages = []
     281    seen = set()
    259282
    260283    for prefix in PREFIXES:
    261284        if not prefix or prefix in seen:
    262285            continue
    263         seen.append(prefix)
     286        seen.add(prefix)
    264287
    265288        if sys.platform in ('os2emx', 'riscos'):
    266             sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
     289            sitepackages.append(os.path.join(prefix, "Lib", "site-packages"))
    267290        elif sys.platform == 'os2knix':
    268291            sitedirs.append(os.path.join(prefix, "lib",
     
    271294            sitedirs.append(os.path.join(prefix, "lib", "site-packages"))
    272295        elif os.sep == '/':
    273             sitedirs.append(os.path.join(prefix, "lib",
     296            sitepackages.append(os.path.join(prefix, "lib",
    274297                                        "python" + sys.version[:3],
    275298                                        "site-packages"))
    276             sitedirs.append(os.path.join(prefix, "lib", "site-python"))
     299            sitepackages.append(os.path.join(prefix, "lib", "site-python"))
    277300        else:
    278             sitedirs.append(prefix)
    279             sitedirs.append(os.path.join(prefix, "lib", "site-packages"))
    280 
     301            sitepackages.append(prefix)
     302            sitepackages.append(os.path.join(prefix, "lib", "site-packages"))
    281303        if sys.platform == "darwin":
    282304            # for framework builds *only* we add the standard Apple
    283             # locations. Currently only per-user, but /Library and
    284             # /Network/Library could be added too
    285             if 'Python.framework' in prefix:
    286                 sitedirs.append(
    287                     os.path.expanduser(
    288                         os.path.join("~", "Library", "Python",
    289                                      sys.version[:3], "site-packages")))
    290 
    291     for sitedir in sitedirs:
     305            # locations.
     306            from sysconfig import get_config_var
     307            framework = get_config_var("PYTHONFRAMEWORK")
     308            if framework:
     309                sitepackages.append(
     310                        os.path.join("/Library", framework,
     311                            sys.version[:3], "site-packages"))
     312    return sitepackages
     313
     314def addsitepackages(known_paths):
     315    """Add site-packages (and possibly site-python) to sys.path"""
     316    for sitedir in getsitepackages():
    292317        if os.path.isdir(sitedir):
    293318            addsitedir(sitedir, known_paths)
    294319
    295320    return known_paths
    296 
    297321
    298322def setBEGINLIBPATH():
     
    314338
    315339def setquit():
    316     """Define new built-ins 'quit' and 'exit'.
    317     These are simply strings that display a hint on how to exit.
     340    """Define new builtins 'quit' and 'exit'.
     341
     342    These are objects which make the interpreter exit when called.
     343    The repr of each object contains a hint at how it works.
    318344
    319345    """
     
    422448
    423449class _Helper(object):
    424     """Define the built-in 'help'.
     450    """Define the builtin 'help'.
    425451    This is a wrapper around pydoc.help (with a twist).
    426452
     
    478504    except ImportError:
    479505        pass
     506    except Exception:
     507        if sys.flags.verbose:
     508            sys.excepthook(*sys.exc_info())
     509        else:
     510            print >>sys.stderr, \
     511                "'import sitecustomize' failed; use -v for traceback"
    480512
    481513
     
    486518    except ImportError:
    487519        pass
     520    except Exception:
     521        if sys.flags.verbose:
     522            sys.excepthook(*sys.exc_info())
     523        else:
     524            print>>sys.stderr, \
     525                "'import usercustomize' failed; use -v for traceback"
    488526
    489527
     
    493531    abs__file__()
    494532    known_paths = removeduppaths()
    495     if ((os.name == "posix" or os.name == "os2") and
    496         sys.path and os.path.basename(sys.path[-1]) == "Modules"):
    497         addbuilddir()
    498         if (os.name == "os2"):
    499             setBEGINLIBPATH()
    500533    if ENABLE_USER_SITE is None:
    501534        ENABLE_USER_SITE = check_enableusersite()
    502535    known_paths = addusersitepackages(known_paths)
    503536    known_paths = addsitepackages(known_paths)
     537    if os.name == "os2":
     538        setBEGINLIBPATH()
    504539    setquit()
    505540    setcopyright()
Note: See TracChangeset for help on using the changeset viewer.