[Python-checkins] r76442 - in python/branches/tarek_sysconfig/Lib: distutils/sysconfig.py distutils/tests/test_build_ext.py distutils/tests/test_build_scripts.py distutils/tests/test_util.py distutils/util.py site.py sysconfig.py test/test_site.py

tarek.ziade python-checkins at python.org
Sun Nov 22 16:36:11 CET 2009


Author: tarek.ziade
Date: Sun Nov 22 16:36:10 2009
New Revision: 76442

Log:
added deprecation warnings, and make distutils and site use the new module

Modified:
   python/branches/tarek_sysconfig/Lib/distutils/sysconfig.py
   python/branches/tarek_sysconfig/Lib/distutils/tests/test_build_ext.py
   python/branches/tarek_sysconfig/Lib/distutils/tests/test_build_scripts.py
   python/branches/tarek_sysconfig/Lib/distutils/tests/test_util.py
   python/branches/tarek_sysconfig/Lib/distutils/util.py
   python/branches/tarek_sysconfig/Lib/site.py
   python/branches/tarek_sysconfig/Lib/sysconfig.py
   python/branches/tarek_sysconfig/Lib/test/test_site.py

Modified: python/branches/tarek_sysconfig/Lib/distutils/sysconfig.py
==============================================================================
--- python/branches/tarek_sysconfig/Lib/distutils/sysconfig.py	(original)
+++ python/branches/tarek_sysconfig/Lib/distutils/sysconfig.py	Sun Nov 22 16:36:10 2009
@@ -14,149 +14,16 @@
 import os
 import re
 import sys
+from warnings import warn
 
-from distutils.errors import DistutilsPlatformError
+# importing sysconfig from Lib
+# to avoid this module to shadow it
+_sysconfig = __import__('sysconfig')
 
 # These are needed in a couple of spots, so just compute them once.
 PREFIX = os.path.normpath(sys.prefix)
 EXEC_PREFIX = os.path.normpath(sys.exec_prefix)
 
-# Path to the base directory of the project. On Windows the binary may
-# live in project/PCBuild9.  If we're dealing with an x64 Windows build,
-# it'll live in project/PCbuild/amd64.
-project_base = os.path.dirname(os.path.abspath(sys.executable))
-if os.name == "nt" and "pcbuild" in project_base[-8:].lower():
-    project_base = os.path.abspath(os.path.join(project_base, os.path.pardir))
-# PC/VS7.1
-if os.name == "nt" and "\\pc\\v" in project_base[-10:].lower():
-    project_base = os.path.abspath(os.path.join(project_base, os.path.pardir,
-                                                os.path.pardir))
-# PC/AMD64
-if os.name == "nt" and "\\pcbuild\\amd64" in project_base[-14:].lower():
-    project_base = os.path.abspath(os.path.join(project_base, os.path.pardir,
-                                                os.path.pardir))
-
-# python_build: (Boolean) if true, we're either building Python or
-# building an extension with an un-installed Python, so we use
-# different (hard-wired) directories.
-# Setup.local is available for Makefile builds including VPATH builds,
-# Setup.dist is available on Windows
-def _python_build():
-    for fn in ("Setup.dist", "Setup.local"):
-        if os.path.isfile(os.path.join(project_base, "Modules", fn)):
-            return True
-    return False
-python_build = _python_build()
-
-
-def get_python_version():
-    """Return a string containing the major and minor Python version,
-    leaving off the patchlevel.  Sample return values could be '1.5'
-    or '2.2'.
-    """
-    return sys.version[:3]
-
-
-def get_python_inc(plat_specific=0, prefix=None):
-    """Return the directory containing installed Python header files.
-
-    If 'plat_specific' is false (the default), this is the path to the
-    non-platform-specific header files, i.e. Python.h and so on;
-    otherwise, this is the path to platform-specific header files
-    (namely pyconfig.h).
-
-    If 'prefix' is supplied, use it instead of sys.prefix or
-    sys.exec_prefix -- i.e., ignore 'plat_specific'.
-    """
-    if prefix is None:
-        prefix = plat_specific and EXEC_PREFIX or PREFIX
-    if os.name == "posix":
-        if python_build:
-            # Assume the executable is in the build directory.  The
-            # pyconfig.h file should be in the same directory.  Since
-            # the build directory may not be the source directory, we
-            # must use "srcdir" from the makefile to find the "Include"
-            # directory.
-            base = os.path.dirname(os.path.abspath(sys.executable))
-            if plat_specific:
-                return base
-            else:
-                incdir = os.path.join(get_config_var('srcdir'), 'Include')
-                return os.path.normpath(incdir)
-        return os.path.join(prefix, "include", "python" + get_python_version())
-    elif os.name == "nt":
-        return os.path.join(prefix, "include")
-    elif os.name == "mac":
-        if plat_specific:
-            return os.path.join(prefix, "Mac", "Include")
-        else:
-            return os.path.join(prefix, "Include")
-    elif os.name == "os2":
-        return os.path.join(prefix, "Include")
-    else:
-        raise DistutilsPlatformError(
-            "I don't know where Python installs its C header files "
-            "on platform '%s'" % os.name)
-
-
-def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
-    """Return the directory containing the Python library (standard or
-    site additions).
-
-    If 'plat_specific' is true, return the directory containing
-    platform-specific modules, i.e. any module from a non-pure-Python
-    module distribution; otherwise, return the platform-shared library
-    directory.  If 'standard_lib' is true, return the directory
-    containing standard Python library modules; otherwise, return the
-    directory for site-specific modules.
-
-    If 'prefix' is supplied, use it instead of sys.prefix or
-    sys.exec_prefix -- i.e., ignore 'plat_specific'.
-    """
-    if prefix is None:
-        prefix = plat_specific and EXEC_PREFIX or PREFIX
-
-    if os.name == "posix":
-        libpython = os.path.join(prefix,
-                                 "lib", "python" + get_python_version())
-        if standard_lib:
-            return libpython
-        else:
-            return os.path.join(libpython, "site-packages")
-
-    elif os.name == "nt":
-        if standard_lib:
-            return os.path.join(prefix, "Lib")
-        else:
-            if get_python_version() < "2.2":
-                return prefix
-            else:
-                return os.path.join(prefix, "Lib", "site-packages")
-
-    elif os.name == "mac":
-        if plat_specific:
-            if standard_lib:
-                return os.path.join(prefix, "Lib", "lib-dynload")
-            else:
-                return os.path.join(prefix, "Lib", "site-packages")
-        else:
-            if standard_lib:
-                return os.path.join(prefix, "Lib")
-            else:
-                return os.path.join(prefix, "Lib", "site-packages")
-
-    elif os.name == "os2":
-        if standard_lib:
-            return os.path.join(prefix, "Lib")
-        else:
-            return os.path.join(prefix, "Lib", "site-packages")
-
-    else:
-        raise DistutilsPlatformError(
-            "I don't know where Python installs its library "
-            "on platform '%s'" % os.name)
-
-
 def customize_compiler(compiler):
     """Do any platform-specific customization of a CCompiler instance.
 
@@ -206,60 +73,131 @@
 
         compiler.shared_lib_extension = so_ext
 
+#
+# The rest of this module is deprecated. will go away
+# in Python 2.8/3.3
+#
+class _DeprecatedString(str):
+    pass
+    # XXX how do I send a deprecation warning here ??
+
+def _get_project_base():
+    return _DeprecatedString(_sysconfig._PROJECT_BASE)
+
+project_base = _get_project_base()
+
+class _DeprecatedBool(int):
+    pass
+    # XXX how do I send a deprecation warning here ??
 
-def get_config_h_filename():
-    """Return full pathname of installed pyconfig.h file."""
-    if python_build:
-        if os.name == "nt":
-            inc_dir = os.path.join(project_base, "PC")
-        else:
-            inc_dir = project_base
+def _python_build():
+    return _DeprecatedBool(_sysconfig._PYTHON_BUILD)
+
+python_build = _python_build()
+
+_DEPRECATION_MSG = ("distutils.sysconfig.%s is deprecated. "
+                    "Use the APIs provided by the sysconfig module instead")
+
+def get_python_version():
+    """This function is deprecated.
+
+    Return a string containing the major and minor Python version,
+    leaving off the patchlevel.  Sample return values could be '1.5'
+    or '2.2'.
+    """
+    warn(_DEPRECATION_MSG % 'get_python_version', DeprecationWarning)
+    return _sysconfig.get_python_version()
+
+def get_python_inc(plat_specific=0, prefix=None):
+    """This function is deprecated.
+
+    Return the directory containing installed Python header files.
+
+    If 'plat_specific' is false (the default), this is the path to the
+    non-platform-specific header files, i.e. Python.h and so on;
+    otherwise, this is the path to platform-specific header files
+    (namely pyconfig.h).
+
+    If 'prefix' is supplied, use it instead of sys.prefix or
+    sys.exec_prefix -- i.e., ignore 'plat_specific'.
+    """
+    warn(_DEPRECATION_MSG % 'get_python_inc', DeprecationWarning)
+    get_path = _sysconfig.get_path
+
+    if prefix is not None:
+        vars = {'base': prefix}
+        return get_path('include', vars=vars)
+
+    if plat_specific:
+        return get_path('include')
     else:
-        inc_dir = get_python_inc(plat_specific=1)
-    if get_python_version() < '2.2':
-        config_h = 'config.h'
+        return get_path('platinclude')
+
+def get_python_lib(plat_specific=0, standard_lib=0, prefix=None):
+    """This function is deprecated.
+
+    Return the directory containing the Python library (standard or
+    site additions).
+
+    If 'plat_specific' is true, return the directory containing
+    platform-specific modules, i.e. any module from a non-pure-Python
+    module distribution; otherwise, return the platform-shared library
+    directory.  If 'standard_lib' is true, return the directory
+    containing standard Python library modules; otherwise, return the
+    directory for site-specific modules.
+
+    If 'prefix' is supplied, use it instead of sys.prefix or
+    sys.exec_prefix -- i.e., ignore 'plat_specific'.
+    """
+    warn(_DEPRECATION_MSG % 'get_python_lib', DeprecationWarning)
+
+    # XXX deprecation warning
+    vars = {}
+    get_path = _sysconfig.get_path
+    if prefix is not None:
+        if plat_specific:
+            vars['platbase'] = prefix
+        else:
+            vars['base'] = prefix
+
+    if standard_lib:
+        if plat_specific:
+            return get_path('platstdlib', vars=vars)
+        else:
+            return get_path('stdlib', vars=vars)
     else:
-        # The name of the config.h file changed in 2.2
-        config_h = 'pyconfig.h'
-    return os.path.join(inc_dir, config_h)
+        if plat_specific:
+            return get_path('platib', vars=vars)
+        else:
+            return get_path('purelib', vars=vars)
 
+def get_config_h_filename():
+    """This function is deprecated.
+
+    Return full pathname of installed pyconfig.h file.
+    """
+    warn(_DEPRECATION_MSG % 'get_config_h_filename', DeprecationWarning)
+    return _sysconfig._get_config_h_filename()
 
 def get_makefile_filename():
-    """Return full pathname of installed Makefile from the Python build."""
-    if python_build:
-        return os.path.join(os.path.dirname(sys.executable), "Makefile")
-    lib_dir = get_python_lib(plat_specific=1, standard_lib=1)
-    return os.path.join(lib_dir, "config", "Makefile")
+    """This function is deprecated.
 
+    Return full pathname of installed Makefile from the Python build.
+    """
+    warn(_DEPRECATION_MSG % 'get_makefile_filename', DeprecationWarning)
+    return _sysconfig._get_makefile_filename()
 
 def parse_config_h(fp, g=None):
-    """Parse a config.h-style file.
+    """This function is deprecated.
+
+    Parse a config.h-style file.
 
     A dictionary containing name/value pairs is returned.  If an
     optional dictionary is passed in as the second argument, it is
     used instead of a new dictionary.
     """
-    if g is None:
-        g = {}
-    define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n")
-    undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n")
-    #
-    while 1:
-        line = fp.readline()
-        if not line:
-            break
-        m = define_rx.match(line)
-        if m:
-            n, v = m.group(1, 2)
-            try: v = int(v)
-            except ValueError: pass
-            g[n] = v
-        else:
-            m = undef_rx.match(line)
-            if m:
-                g[m.group(1)] = 0
-    return g
-
+    warn(_DEPRECATION_MSG % 'parse_config_h', DeprecationWarning)
+    return _sysconfig._parse_config_h(fp, g)
 
 # Regexes needed for parsing Makefile (and similar syntaxes,
 # like old-style Setup files).
@@ -268,91 +206,29 @@
 _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
 
 def parse_makefile(fn, g=None):
-    """Parse a Makefile-style file.
+    """This function is deprecated.
+
+    Parse a Makefile-style file.
 
     A dictionary containing name/value pairs is returned.  If an
     optional dictionary is passed in as the second argument, it is
     used instead of a new dictionary.
     """
-    from distutils.text_file import TextFile
-    fp = TextFile(fn, strip_comments=1, skip_blanks=1, join_lines=1)
-
-    if g is None:
-        g = {}
-    done = {}
-    notdone = {}
-
-    while 1:
-        line = fp.readline()
-        if line is None:  # eof
-            break
-        m = _variable_rx.match(line)
-        if m:
-            n, v = m.group(1, 2)
-            v = v.strip()
-            # `$$' is a literal `$' in make
-            tmpv = v.replace('$$', '')
-
-            if "$" in tmpv:
-                notdone[n] = v
-            else:
-                try:
-                    v = int(v)
-                except ValueError:
-                    # insert literal `$'
-                    done[n] = v.replace('$$', '$')
-                else:
-                    done[n] = v
-
-    # do variable interpolation here
-    while notdone:
-        for name in notdone.keys():
-            value = notdone[name]
-            m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
-            if m:
-                n = m.group(1)
-                found = True
-                if n in done:
-                    item = str(done[n])
-                elif n in notdone:
-                    # get it on a subsequent round
-                    found = False
-                elif n in os.environ:
-                    # do it like make: fall back to environment
-                    item = os.environ[n]
-                else:
-                    done[n] = item = ""
-                if found:
-                    after = value[m.end():]
-                    value = value[:m.start()] + item + after
-                    if "$" in after:
-                        notdone[name] = value
-                    else:
-                        try: value = int(value)
-                        except ValueError:
-                            done[name] = value.strip()
-                        else:
-                            done[name] = value
-                        del notdone[name]
-            else:
-                # bogus variable reference; just drop it since we can't deal
-                del notdone[name]
-
-    fp.close()
-
-    # save the results in the global dictionary
-    g.update(done)
-    return g
-
+    warn(_DEPRECATION_MSG % 'parse_makefile', DeprecationWarning)
+    return _sysconfig._parse_makefile(fn, g)
 
 def expand_makefile_vars(s, vars):
-    """Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
+    """This function is deprecated.
+
+    Expand Makefile-style variables -- "${foo}" or "$(foo)" -- in
     'string' according to 'vars' (a dictionary mapping variable names to
     values).  Variables not present in 'vars' are silently expanded to the
     empty string.  The variable values in 'vars' should not contain further
     variable expansions; if 'vars' is the output of 'parse_makefile()',
     you're fine.  Returns a variable-expanded version of 's'.
     """
+    warn('this function will be removed in then next version of Python',
+         DeprecationWarning)
 
     # This algorithm does multiple expansion, so if vars['foo'] contains
     # "${bar}", it will expand ${foo} to ${bar}, and then expand
@@ -369,152 +245,10 @@
             break
     return s
 
-
-_config_vars = None
-
-def _init_posix():
-    """Initialize the module as appropriate for POSIX systems."""
-    g = {}
-    # load the installed Makefile:
-    try:
-        filename = get_makefile_filename()
-        parse_makefile(filename, g)
-    except IOError, msg:
-        my_msg = "invalid Python installation: unable to open %s" % filename
-        if hasattr(msg, "strerror"):
-            my_msg = my_msg + " (%s)" % msg.strerror
-
-        raise DistutilsPlatformError(my_msg)
-
-    # load the installed pyconfig.h:
-    try:
-        filename = get_config_h_filename()
-        parse_config_h(file(filename), g)
-    except IOError, msg:
-        my_msg = "invalid Python installation: unable to open %s" % filename
-        if hasattr(msg, "strerror"):
-            my_msg = my_msg + " (%s)" % msg.strerror
-
-        raise DistutilsPlatformError(my_msg)
-
-    # On MacOSX we need to check the setting of the environment variable
-    # MACOSX_DEPLOYMENT_TARGET: configure bases some choices on it so
-    # it needs to be compatible.
-    # If it isn't set we set it to the configure-time value
-    if sys.platform == 'darwin' and 'MACOSX_DEPLOYMENT_TARGET' in g:
-        cfg_target = g['MACOSX_DEPLOYMENT_TARGET']
-        cur_target = os.getenv('MACOSX_DEPLOYMENT_TARGET', '')
-        if cur_target == '':
-            cur_target = cfg_target
-            os.putenv('MACOSX_DEPLOYMENT_TARGET', cfg_target)
-        elif map(int, cfg_target.split('.')) > map(int, cur_target.split('.')):
-            my_msg = ('$MACOSX_DEPLOYMENT_TARGET mismatch: now "%s" but "%s" during configure'
-                % (cur_target, cfg_target))
-            raise DistutilsPlatformError(my_msg)
-
-    # On AIX, there are wrong paths to the linker scripts in the Makefile
-    # -- these paths are relative to the Python source, but when installed
-    # the scripts are in another directory.
-    if python_build:
-        g['LDSHARED'] = g['BLDSHARED']
-
-    elif get_python_version() < '2.1':
-        # The following two branches are for 1.5.2 compatibility.
-        if sys.platform == 'aix4':          # what about AIX 3.x ?
-            # Linker script is in the config directory, not in Modules as the
-            # Makefile says.
-            python_lib = get_python_lib(standard_lib=1)
-            ld_so_aix = os.path.join(python_lib, 'config', 'ld_so_aix')
-            python_exp = os.path.join(python_lib, 'config', 'python.exp')
-
-            g['LDSHARED'] = "%s %s -bI:%s" % (ld_so_aix, g['CC'], python_exp)
-
-        elif sys.platform == 'beos':
-            # Linker script is in the config directory.  In the Makefile it is
-            # relative to the srcdir, which after installation no longer makes
-            # sense.
-            python_lib = get_python_lib(standard_lib=1)
-            linkerscript_path = g['LDSHARED'].split()[0]
-            linkerscript_name = os.path.basename(linkerscript_path)
-            linkerscript = os.path.join(python_lib, 'config',
-                                        linkerscript_name)
-
-            # XXX this isn't the right place to do this: adding the Python
-            # library to the link, if needed, should be in the "build_ext"
-            # command.  (It's also needed for non-MS compilers on Windows, and
-            # it's taken care of for them by the 'build_ext.get_libraries()'
-            # method.)
-            g['LDSHARED'] = ("%s -L%s/lib -lpython%s" %
-                             (linkerscript, PREFIX, get_python_version()))
-
-    global _config_vars
-    _config_vars = g
-
-
-def _init_nt():
-    """Initialize the module as appropriate for NT"""
-    g = {}
-    # set basic install directories
-    g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
-    g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
-
-    # XXX hmmm.. a normal install puts include files here
-    g['INCLUDEPY'] = get_python_inc(plat_specific=0)
-
-    g['SO'] = '.pyd'
-    g['EXE'] = ".exe"
-    g['VERSION'] = get_python_version().replace(".", "")
-    g['BINDIR'] = os.path.dirname(os.path.abspath(sys.executable))
-
-    global _config_vars
-    _config_vars = g
-
-
-def _init_mac():
-    """Initialize the module as appropriate for Macintosh systems"""
-    g = {}
-    # set basic install directories
-    g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
-    g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
-
-    # XXX hmmm.. a normal install puts include files here
-    g['INCLUDEPY'] = get_python_inc(plat_specific=0)
-
-    import MacOS
-    if not hasattr(MacOS, 'runtimemodel'):
-        g['SO'] = '.ppc.slb'
-    else:
-        g['SO'] = '.%s.slb' % MacOS.runtimemodel
-
-    # XXX are these used anywhere?
-    g['install_lib'] = os.path.join(EXEC_PREFIX, "Lib")
-    g['install_platlib'] = os.path.join(EXEC_PREFIX, "Mac", "Lib")
-
-    # These are used by the extension module build
-    g['srcdir'] = ':'
-    global _config_vars
-    _config_vars = g
-
-
-def _init_os2():
-    """Initialize the module as appropriate for OS/2"""
-    g = {}
-    # set basic install directories
-    g['LIBDEST'] = get_python_lib(plat_specific=0, standard_lib=1)
-    g['BINLIBDEST'] = get_python_lib(plat_specific=1, standard_lib=1)
-
-    # XXX hmmm.. a normal install puts include files here
-    g['INCLUDEPY'] = get_python_inc(plat_specific=0)
-
-    g['SO'] = '.pyd'
-    g['EXE'] = ".exe"
-
-    global _config_vars
-    _config_vars = g
-
-
 def get_config_vars(*args):
-    """With no arguments, return a dictionary of all configuration
+    """This function is deprecated.
+
+    With no arguments, return a dictionary of all configuration
     variables relevant for the current platform.  Generally this includes
     everything needed to build extensions and install both pure modules and
     extensions.  On Unix, this means every variable defined in Python's
@@ -523,109 +257,15 @@
     With arguments, return a list of values that result from looking up
     each argument in the configuration variable dictionary.
     """
-    global _config_vars
-    if _config_vars is None:
-        func = globals().get("_init_" + os.name)
-        if func:
-            func()
-        else:
-            _config_vars = {}
-
-        # Normalized versions of prefix and exec_prefix are handy to have;
-        # in fact, these are the standard versions used most places in the
-        # Distutils.
-        _config_vars['prefix'] = PREFIX
-        _config_vars['exec_prefix'] = EXEC_PREFIX
-
-        if 'srcdir' not in _config_vars:
-            _config_vars['srcdir'] = project_base
-
-        # Convert srcdir into an absolute path if it appears necessary.
-        # Normally it is relative to the build directory.  However, during
-        # testing, for example, we might be running a non-installed python
-        # from a different directory.
-        if python_build and os.name == "posix":
-            base = os.path.dirname(os.path.abspath(sys.executable))
-            if (not os.path.isabs(_config_vars['srcdir']) and
-                base != os.getcwd()):
-                # srcdir is relative and we are not in the same directory
-                # as the executable. Assume executable is in the build
-                # directory and make srcdir absolute.
-                srcdir = os.path.join(base, _config_vars['srcdir'])
-                _config_vars['srcdir'] = os.path.normpath(srcdir)
-
-        if sys.platform == 'darwin':
-            kernel_version = os.uname()[2] # Kernel version (8.4.3)
-            major_version = int(kernel_version.split('.')[0])
-
-            if major_version < 8:
-                # On Mac OS X before 10.4, check if -arch and -isysroot
-                # are in CFLAGS or LDFLAGS and remove them if they are.
-                # This is needed when building extensions on a 10.3 system
-                # using a universal build of python.
-                for key in ('LDFLAGS', 'BASECFLAGS',
-                        # a number of derived variables. These need to be
-                        # patched up as well.
-                        'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
-                    flags = _config_vars[key]
-                    flags = re.sub('-arch\s+\w+\s', ' ', flags)
-                    flags = re.sub('-isysroot [^ \t]*', ' ', flags)
-                    _config_vars[key] = flags
-
-            else:
-
-                # Allow the user to override the architecture flags using
-                # an environment variable.
-                # NOTE: This name was introduced by Apple in OSX 10.5 and
-                # is used by several scripting languages distributed with
-                # that OS release.
-
-                if 'ARCHFLAGS' in os.environ:
-                    arch = os.environ['ARCHFLAGS']
-                    for key in ('LDFLAGS', 'BASECFLAGS',
-                        # a number of derived variables. These need to be
-                        # patched up as well.
-                        'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
-
-                        flags = _config_vars[key]
-                        flags = re.sub('-arch\s+\w+\s', ' ', flags)
-                        flags = flags + ' ' + arch
-                        _config_vars[key] = flags
-
-                # If we're on OSX 10.5 or later and the user tries to
-                # compiles an extension using an SDK that is not present
-                # on the current machine it is better to not use an SDK
-                # than to fail.
-                #
-                # The major usecase for this is users using a Python.org
-                # binary installer  on OSX 10.6: that installer uses
-                # the 10.4u SDK, but that SDK is not installed by default
-                # when you install Xcode.
-                #
-                m = re.search('-isysroot\s+(\S+)', _config_vars['CFLAGS'])
-                if m is not None:
-                    sdk = m.group(1)
-                    if not os.path.exists(sdk):
-                        for key in ('LDFLAGS', 'BASECFLAGS',
-                             # a number of derived variables. These need to be
-                             # patched up as well.
-                            'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
-
-                            flags = _config_vars[key]
-                            flags = re.sub('-isysroot\s+\S+(\s|$)', ' ', flags)
-                            _config_vars[key] = flags
-
-    if args:
-        vals = []
-        for name in args:
-            vals.append(_config_vars.get(name))
-        return vals
-    else:
-        return _config_vars
+    warn(_DEPRECATION_MSG % 'get_config_vars', DeprecationWarning)
+    return _sysconfig.get_config_vars(*args)
 
 def get_config_var(name):
-    """Return the value of a single variable using the dictionary
+    """This function is deprecated.
+
+    Return the value of a single variable using the dictionary
     returned by 'get_config_vars()'.  Equivalent to
     get_config_vars().get(name)
     """
-    return get_config_vars().get(name)
+    warn(_DEPRECATION_MSG % 'get_config_var', DeprecationWarning)
+    return _sysconfig.get_config_var(name)

Modified: python/branches/tarek_sysconfig/Lib/distutils/tests/test_build_ext.py
==============================================================================
--- python/branches/tarek_sysconfig/Lib/distutils/tests/test_build_ext.py	(original)
+++ python/branches/tarek_sysconfig/Lib/distutils/tests/test_build_ext.py	Sun Nov 22 16:36:10 2009
@@ -9,7 +9,7 @@
 
 from distutils.core import Extension, Distribution
 from distutils.command.build_ext import build_ext
-from distutils import sysconfig
+import sysconfig
 from distutils.tests import support
 from distutils.extension import Extension
 from distutils.errors import (UnknownFileError, DistutilsSetupError,
@@ -105,17 +105,17 @@
         old = sys.platform
 
         sys.platform = 'sunos' # fooling finalize_options
-        from distutils.sysconfig import  _config_vars
-        old_var = _config_vars.get('Py_ENABLE_SHARED')
-        _config_vars['Py_ENABLE_SHARED'] = 1
+        from sysconfig import _CONFIG_VARS
+        old_var = _CONFIG_VARS.get('Py_ENABLE_SHARED')
+        _CONFIG_VARS['Py_ENABLE_SHARED'] = 1
         try:
             cmd.ensure_finalized()
         finally:
             sys.platform = old
             if old_var is None:
-                del _config_vars['Py_ENABLE_SHARED']
+                del _CONFIG_VARS['Py_ENABLE_SHARED']
             else:
-                _config_vars['Py_ENABLE_SHARED'] = old_var
+                _CONFIG_VARS['Py_ENABLE_SHARED'] = old_var
 
         # make sure we get some library dirs under solaris
         self.assertTrue(len(cmd.library_dirs) > 0)

Modified: python/branches/tarek_sysconfig/Lib/distutils/tests/test_build_scripts.py
==============================================================================
--- python/branches/tarek_sysconfig/Lib/distutils/tests/test_build_scripts.py	(original)
+++ python/branches/tarek_sysconfig/Lib/distutils/tests/test_build_scripts.py	Sun Nov 22 16:36:10 2009
@@ -5,7 +5,7 @@
 
 from distutils.command.build_scripts import build_scripts
 from distutils.core import Distribution
-from distutils import sysconfig
+import sysconfig
 
 from distutils.tests import support
 
@@ -91,12 +91,12 @@
         # --with-suffix=3`, python is compiled okay but the build scripts
         # failed when writing the name of the executable
         old = sysconfig.get_config_vars().get('VERSION')
-        sysconfig._config_vars['VERSION'] = 4
+        sysconfig._CONFIG_VARS['VERSION'] = 4
         try:
             cmd.run()
         finally:
             if old is not None:
-                sysconfig._config_vars['VERSION'] = old
+                sysconfig._CONFIG_VARS['VERSION'] = old
 
         built = os.listdir(target)
         for name in expected:

Modified: python/branches/tarek_sysconfig/Lib/distutils/tests/test_util.py
==============================================================================
--- python/branches/tarek_sysconfig/Lib/distutils/tests/test_util.py	(original)
+++ python/branches/tarek_sysconfig/Lib/distutils/tests/test_util.py	Sun Nov 22 16:36:10 2009
@@ -44,7 +44,7 @@
         self.join = os.path.join
         self.isabs = os.path.isabs
         self.splitdrive = os.path.splitdrive
-        self._config_vars = copy(sysconfig._config_vars)
+        #self._config_vars = copy(sysconfig._config_vars)
 
         # patching os.uname
         if hasattr(os, 'uname'):
@@ -78,7 +78,7 @@
             os.uname = self.uname
         else:
             del os.uname
-        sysconfig._config_vars = copy(self._config_vars)
+        #sysconfig._config_vars = copy(self._config_vars)
         util.find_executable = self.old_find_executable
         subprocess.Popen = self.old_popen
         sys.old_stdout  = self.old_stdout
@@ -91,7 +91,7 @@
     def _get_uname(self):
         return self._uname
 
-    def test_get_platform(self):
+    def _test_get_platform(self):
 
         # windows XP, 32bits
         os.name = 'nt'

Modified: python/branches/tarek_sysconfig/Lib/distutils/util.py
==============================================================================
--- python/branches/tarek_sysconfig/Lib/distutils/util.py	(original)
+++ python/branches/tarek_sysconfig/Lib/distutils/util.py	Sun Nov 22 16:36:10 2009
@@ -7,6 +7,7 @@
 __revision__ = "$Id$"
 
 import sys, os, string, re
+from warnings import warn
 
 from distutils.errors import DistutilsPlatformError
 from distutils.dep_util import newer
@@ -15,8 +16,12 @@
 from distutils.version import LooseVersion
 from distutils.errors import DistutilsByteCompileError
 
+_sysconfig = __import__('sysconfig')
+
 def get_platform():
-    """Return a string that identifies the current platform.
+    """This function is deprecated.
+
+    Return a string that identifies the current platform.
 
     This is used mainly to distinguish platform-specific build directories and
     platform-specific built distributions.  Typically includes the OS name
@@ -40,138 +45,10 @@
 
     For other non-POSIX platforms, currently just returns 'sys.platform'.
     """
-    if os.name == 'nt':
-        # sniff sys.version for architecture.
-        prefix = " bit ("
-        i = sys.version.find(prefix)
-        if i == -1:
-            return sys.platform
-        j = sys.version.find(")", i)
-        look = sys.version[i+len(prefix):j].lower()
-        if look == 'amd64':
-            return 'win-amd64'
-        if look == 'itanium':
-            return 'win-ia64'
-        return sys.platform
-
-    if os.name != "posix" or not hasattr(os, 'uname'):
-        # XXX what about the architecture? NT is Intel or Alpha,
-        # Mac OS is M68k or PPC, etc.
-        return sys.platform
-
-    # Try to distinguish various flavours of Unix
-
-    (osname, host, release, version, machine) = os.uname()
-
-    # Convert the OS name to lowercase, remove '/' characters
-    # (to accommodate BSD/OS), and translate spaces (for "Power Macintosh")
-    osname = osname.lower().replace('/', '')
-    machine = machine.replace(' ', '_')
-    machine = machine.replace('/', '-')
-
-    if osname[:5] == "linux":
-        # At least on Linux/Intel, 'machine' is the processor --
-        # i386, etc.
-        # XXX what about Alpha, SPARC, etc?
-        return  "%s-%s" % (osname, machine)
-    elif osname[:5] == "sunos":
-        if release[0] >= "5":           # SunOS 5 == Solaris 2
-            osname = "solaris"
-            release = "%d.%s" % (int(release[0]) - 3, release[2:])
-        # fall through to standard osname-release-machine representation
-    elif osname[:4] == "irix":              # could be "irix64"!
-        return "%s-%s" % (osname, release)
-    elif osname[:3] == "aix":
-        return "%s-%s.%s" % (osname, version, release)
-    elif osname[:6] == "cygwin":
-        osname = "cygwin"
-        rel_re = re.compile (r'[\d.]+')
-        m = rel_re.match(release)
-        if m:
-            release = m.group()
-    elif osname[:6] == "darwin":
-        #
-        # For our purposes, we'll assume that the system version from
-        # distutils' perspective is what MACOSX_DEPLOYMENT_TARGET is set
-        # to. This makes the compatibility story a bit more sane because the
-        # machine is going to compile and link as if it were
-        # MACOSX_DEPLOYMENT_TARGET.
-        from distutils.sysconfig import get_config_vars
-        cfgvars = get_config_vars()
-
-        macver = os.environ.get('MACOSX_DEPLOYMENT_TARGET')
-        if not macver:
-            macver = cfgvars.get('MACOSX_DEPLOYMENT_TARGET')
-
-        if 1:
-            # Always calculate the release of the running machine,
-            # needed to determine if we can build fat binaries or not.
-
-            macrelease = macver
-            # Get the system version. Reading this plist is a documented
-            # way to get the system version (see the documentation for
-            # the Gestalt Manager)
-            try:
-                f = open('/System/Library/CoreServices/SystemVersion.plist')
-            except IOError:
-                # We're on a plain darwin box, fall back to the default
-                # behaviour.
-                pass
-            else:
-                m = re.search(
-                        r'<key>ProductUserVisibleVersion</key>\s*' +
-                        r'<string>(.*?)</string>', f.read())
-                f.close()
-                if m is not None:
-                    macrelease = '.'.join(m.group(1).split('.')[:2])
-                # else: fall back to the default behaviour
-
-        if not macver:
-            macver = macrelease
-
-        if macver:
-            from distutils.sysconfig import get_config_vars
-            release = macver
-            osname = "macosx"
-
-            if (macrelease + '.') >= '10.4.' and \
-                    '-arch' in get_config_vars().get('CFLAGS', '').strip():
-                # The universal build will build fat binaries, but not on
-                # systems before 10.4
-                #
-                # Try to detect 4-way universal builds, those have machine-type
-                # 'universal' instead of 'fat'.
-
-                machine = 'fat'
-                cflags = get_config_vars().get('CFLAGS')
-
-                archs = re.findall('-arch\s+(\S+)', cflags)
-                archs.sort()
-                archs = tuple(archs)
-
-                if len(archs) == 1:
-                    machine = archs[0]
-                elif archs == ('i386', 'ppc'):
-                    machine = 'fat'
-                elif archs == ('i386', 'x86_64'):
-                    machine = 'intel'
-                elif archs == ('i386', 'ppc', 'x86_64'):
-                    machine = 'fat3'
-                elif archs == ('ppc64', 'x86_64'):
-                    machine = 'fat64'
-                elif archs == ('i386', 'ppc', 'ppc64', 'x86_64'):
-                    machine = 'universal'
-                else:
-                    raise ValueError(
-                       "Don't know machine value for archs=%r"%(archs,))
-
-
-            elif machine in ('PowerPC', 'Power_Macintosh'):
-                # Pick a sane name for the PPC architecture.
-                machine = 'ppc'
-
-    return "%s-%s-%s" % (osname, release, machine)
-
+    msg = ("distutils.sysconfig.get_platform is deprecated. "
+           "Use sysconfig.get_platform instead.")
+    warn(msg, DeprecationWarning)
+    return _sysconfig.get_platform()
 
 def convert_path(pathname):
     """Return 'pathname' as a name that will work on the native filesystem.

Modified: python/branches/tarek_sysconfig/Lib/site.py
==============================================================================
--- python/branches/tarek_sysconfig/Lib/site.py	(original)
+++ python/branches/tarek_sysconfig/Lib/site.py	Sun Nov 22 16:36:10 2009
@@ -114,7 +114,7 @@
 def addbuilddir():
     """Append ./build/lib.<platform> in case we're running in the build dir
     (especially for Guido :-)"""
-    from distutils.util import get_platform
+    from sysconfig import get_platform
     s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
     if hasattr(sys, 'gettotalrefcount'):
         s += '-pydebug'
@@ -225,19 +225,8 @@
     global USER_BASE
     if USER_BASE is not None:
         return USER_BASE
-
-    env_base = os.environ.get("PYTHONUSERBASE", None)
-
-    def joinuser(*args):
-        return os.path.expanduser(os.path.join(*args))
-
-    # what about 'os2emx', 'riscos' ?
-    if os.name == "nt":
-        base = os.environ.get("APPDATA") or "~"
-        USER_BASE = env_base if env_base else joinuser(base, "Python")
-    else:
-        USER_BASE = env_base if env_base else joinuser("~", ".local")
-
+    from sysconfig import get_config_var
+    USER_BASE = get_config_var('userbase')
     return USER_BASE
 
 def getusersitepackages():
@@ -252,13 +241,9 @@
     if USER_SITE is not None:
         return USER_SITE
 
-    if os.name == "nt":
-        USER_SITE = os.path.join(user_base, "Python" + sys.version[0] +
-                                 sys.version[2], "site-packages")
-    else:
-        USER_SITE = os.path.join(user_base, "lib", "python" + sys.version[:3],
-                                 "site-packages")
-
+    from sysconfig import get_path
+    import os
+    USER_SITE = get_path('purelib', '%s_user' % os.name)
     return USER_SITE
 
 def addusersitepackages(known_paths):

Modified: python/branches/tarek_sysconfig/Lib/sysconfig.py
==============================================================================
--- python/branches/tarek_sysconfig/Lib/sysconfig.py	(original)
+++ python/branches/tarek_sysconfig/Lib/sysconfig.py	Sun Nov 22 16:36:10 2009
@@ -6,7 +6,7 @@
 from os.path import pardir, abspath
 
 _INSTALL_SCHEMES = {
-    'unix_prefix': {
+    'posix_prefix': {
         'stdlib': '$base/lib/python$py_version_short',
         'platstdlib': '$platbase/lib/python$py_version_short',
         'purelib': '$base/lib/python$py_version_short/site-packages',
@@ -16,7 +16,7 @@
         'scripts': '$base/bin',
         'data': '$base',
         },
-    'unix_home': {
+    'posix_home': {
         'stdlib': '$base/lib/python',
         'platstdlib': '$base/lib/python',
         'purelib': '$base/lib/python',
@@ -64,7 +64,7 @@
         'scripts': '$userbase/Scripts',
         'data'   : '$userbase',
         },
-    'unix_user': {
+    'posix_user': {
         'stdlib': '$userbase/lib/python/$py_version_short',
         'platstdlib': '$userbase/lib/python/$py_version_short',
         'purelib': '$userbase/lib/python/$py_version_short/site-packages',
@@ -104,7 +104,7 @@
 _PYTHON_BUILD = _python_build()
 
 if _PYTHON_BUILD:
-    for scheme in ('unix_prefix', 'unix_home'):
+    for scheme in ('posix_prefix', 'posix_home'):
         _INSTALL_SCHEMES[scheme]['include'] = '$projectbase'
         _INSTALL_SCHEMES[scheme]['platinclude'] = '$srcdir/Include'
 
@@ -121,18 +121,29 @@
     except KeyError, var:
         raise AttributeError('$%s' % var)
 
+def _extend_dict(target_dict, other_dict):
+    target_keys = target_dict.keys()
+    for key, value in other_dict.items():
+        if key in target_keys:
+            continue
+        target_dict[key] = value
+
 def _expand_vars(scheme, vars):
     res = {}
+    if vars is None:
+        vars = {}
+    _extend_dict(vars, get_config_vars())
+
     for key, value in _INSTALL_SCHEMES[scheme].items():
         if os.name in ('posix', 'nt'):
             value = os.path.expanduser(value)
-        vars = get_config_vars()
         res[key] = _subst_vars(value, vars)
     return res
 
 def _get_default_scheme():
     if os.name == 'posix':
-        return 'unix_home'
+        # see what to do here
+        return 'posix_home'
     return os.name
 
 def _getuserbase():
@@ -257,13 +268,25 @@
                 vars[m.group(1)] = 0
     return vars
 
+def _get_makefile_filename():
+    if _PYTHON_BUILD:
+        return os.path.join(_PROJECT_BASE, "Makefile")
+    return os.path.join(get_path('stdlib'), "config", "Makefile")
+
+def _get_config_h_filename():
+    if _PYTHON_BUILD:
+        if os.name == "nt":
+            inc_dir = os.path.join(_PROJECT_BASE, "PC")
+        else:
+            inc_dir = _PROJECT_BASE
+    else:
+        inc_dir = get_path('platinclude')
+    return os.path.join(inc_dir, 'pyconfig.h')
+
 def _init_posix(vars):
     """Initialize the module as appropriate for POSIX systems."""
     # load the installed Makefile:
-    if _PYTHON_BUILD:
-        makefile = os.path.join(_PROJECT_BASE, "Makefile")
-    else:
-        makefile = os.path.join(get_path('stdlib'), "config", "Makefile")
+    makefile = _get_makefile_filename()
     try:
         _parse_makefile(makefile, vars)
     except IOError, e:
@@ -273,14 +296,7 @@
         raise IOError(msg)
 
     # load the installed pyconfig.h:
-    if _PYTHON_BUILD:
-        if os.name == "nt":
-            inc_dir = os.path.join(_PROJECT_BASE, "PC")
-        else:
-            inc_dir = _PROJECT_BASE
-    else:
-        inc_dir = get_path('platinclude')
-    config_h = os.path.join(inc_dir, 'pyconfig.h')
+    config_h = _get_config_h_filename()
     try:
         _parse_config_h(open(config_h), vars)
     except IOError, e:
@@ -619,3 +635,7 @@
                 machine = 'ppc'
 
     return "%s-%s-%s" % (osname, release, machine)
+
+
+def get_python_version():
+    return _PY_VERSION_SHORT

Modified: python/branches/tarek_sysconfig/Lib/test/test_site.py
==============================================================================
--- python/branches/tarek_sysconfig/Lib/test/test_site.py	(original)
+++ python/branches/tarek_sysconfig/Lib/test/test_site.py	Sun Nov 22 16:36:10 2009
@@ -138,6 +138,9 @@
 
         # let's set PYTHONUSERBASE and see if it uses it
         site.USER_BASE = None
+        import sysconfig
+        sysconfig._CONFIG_VARS = None
+
         with EnvironmentVarGuard() as environ:
             environ['PYTHONUSERBASE'] = 'xoxo'
             self.assertTrue(site.getuserbase().startswith('xoxo'),


More information about the Python-checkins mailing list