distutils msvccompiler contains msvccompiler an implementation of the abstract ccompiler class for the microsoft visual studio written by perry stoll hacked by robin becker and thomas heller to do a better job of finding devstudio through the registry return list of registry keys try handle regopenkeyexbase key except regerror return none l i 0 while true try k regenumkeyhandle i except regerror break l appendk i 1 return l def readvaluesbase key try handle regopenkeyexbase key except regerror return none d i 0 while true try name value type regenumvaluehandle i except regerror break name name lower dconvertmbcsname convertmbcsvalue i 1 return d def convertmbcss dec getattrs decode none if dec is not none try s decmbcs except unicodeerror pass return s class macroexpander def initself version self macros self loadmacrosversion def setmacroself macro path key for base in hkeys d readvaluesbase path if d self macross macro dkey break def loadmacrosself version vsbase rsoftwaremicrosoftvisualstudio0 1f version self setmacrovcinstalldir vsbase rsetupvc productdir self setmacrovsinstalldir vsbase rsetupvs productdir net rsoftwaremicrosoft netframework self setmacroframeworkdir net installroot try if version 7 0 self setmacroframeworksdkdir net sdkinstallrootv1 1 else self setmacroframeworksdkdir net sdkinstallroot except keyerror as exc raise distutilsplatformerror return the version of msvc that was used to build python for python 2 3 and up the version number is included in sys version for earlier versions assume the compiler is msvc 6 v13 was skipped and should be v14 i don t think paths are affected by minor version in version 6 else we don t know what version of the compiler this is return the processor architecture possible results are intel or amd64 return a list of normalized paths with duplicates removed the current order of paths is maintained paths are normalized so things like a and a aren t both preserved xxxnnorwitz on2 if reducedpaths gets long perhaps use a set concrete class that implements an interface to microsoft visual c as defined by the ccompiler abstract class compilertype msvc just set this so ccompiler s constructor doesn t barf we currently don t use the setexecutables bureaucracy provided by ccompiler as it really isn t necessary for this sort of singlecompiler class would be nice to have a consistent interface with unixccompiler though so it s worth thinking about executables private class data need to distinguish c from c source for compiler cextensions c cppextensions cc cpp cxx rcextensions rc mcextensions mc needed for the filename generation methods provided by the base class ccompiler srcextensions cextensions cppextensions rcextensions mcextensions resextension res objextension obj staticlibextension lib sharedlibextension dll staticlibformat sharedlibformat ss exeextension exe def initself verbose0 dryrun0 force0 ccompiler init self verbose dryrun force self version getbuildversion self arch getbuildarchitecture if self arch intel x86 if self version 7 self root rsoftwaremicrosoftvisualstudio self macros macroexpanderself version else self root rsoftwaremicrosoftdevstudio self product visual studio version s self version else win64 assume this was built with the platform sdk self product microsoft sdk compiler s self version 6 self initialized false miscellaneous methods helper methods for using the msvc registry settings def findexeself exe for p in self paths fn os path joinos path abspathp exe if os path isfilefn return fn didn t find it try existing path for p in os environ path split fn os path joinos path abspathp exe if os path isfilefn return fn return exe def getmsvcpathsself path platform x86 if not canreadreg return path path dirs if self version 7 key rs0 1fvcvcobjectsplatforminfowin32directories self root self version else key rs6 0build systemcomponentsplatforms rwin32 sdirectories self root platform for base in hkeys d readvaluesbase key if d if self version 7 return self macros subdpath split else return dpath split msvc 6 seems to create the registry entries we need only when the gui is run if self version 6 for base in hkeys if readvaluesbase rs6 0 self root is not none self warnit seems you have visual studio 6 installed but the expected registry settings are not present n you must at least run the visual studio gui once so that these entries are created break return def setpathenvvarself name if name lib p self getmsvcpathslibrary else p self getmsvcpathsname if p os environname joinp if getbuildversion 8 0 log debugimporting new compiler from distutils msvc9compiler oldmsvccompiler msvccompiler from distutils msvc9compiler import msvccompiler getbuildarchitecture not really relevant now we support crosscompile from distutils msvc9compiler import macroexpander written by perry stoll hacked by robin becker and thomas heller to do a better job of finding devstudio through the registry return list of registry keys return dict of registry keys and values all names are converted to lowercase python was built with visual studio 2003 extensions must be built with a compiler than can generate compatible binaries visual studio 2003 was not found on this system if you have cygwin installed you can try compiling with mingw32 by passing c mingw32 to setup py return the version of msvc that was used to build python for python 2 3 and up the version number is included in sys version for earlier versions assume the compiler is msvc 6 v13 was skipped and should be v14 i don t think paths are affected by minor version in version 6 else we don t know what version of the compiler this is return the processor architecture possible results are intel or amd64 return a list of normalized paths with duplicates removed the current order of paths is maintained paths are normalized so things like a and a aren t both preserved xxx nnorwitz o n 2 if reduced_paths gets long perhaps use a set concrete class that implements an interface to microsoft visual c as defined by the ccompiler abstract class just set this so ccompiler s constructor doesn t barf we currently don t use the set_executables bureaucracy provided by ccompiler as it really isn t necessary for this sort of single compiler class would be nice to have a consistent interface with unixccompiler though so it s worth thinking about private class data need to distinguish c from c source for compiler needed for the filename generation methods provided by the base class ccompiler x86 win64 assume this was built with the platform sdk miscellaneous methods helper methods for using the msvc registry settings return path to an msvc executable program tries to find the program in several places first one of the msvc program search paths from the registry next the directories in the path environment variable if any of those work return an absolute path that is known to exist if none of them work just return the original program name exe didn t find it try existing path get a list of devstudio directories include lib or path return a list of strings the list will be empty if unable to access the registry or appropriate registry keys not found msvc 6 seems to create the registry entries we need only when the gui is run set environment variable name to an msvc path type value this is equivalent to a set command prior to execution of spawned commands get_build_architecture not really relevant now we support cross compile
import sys, os
from distutils.errors import DistutilsPlatformError
from distutils.ccompiler import CCompiler
from distutils import log

_can_read_reg = False
try:
    import winreg

    _can_read_reg = True
    hkey_mod = winreg

    RegOpenKeyEx = winreg.OpenKeyEx
    RegEnumKey = winreg.EnumKey
    RegEnumValue = winreg.EnumValue
    RegError = winreg.error

except ImportError:
    try:
        import win32api
        import win32con
        _can_read_reg = True
        hkey_mod = win32con

        RegOpenKeyEx = win32api.RegOpenKeyEx
        RegEnumKey = win32api.RegEnumKey
        RegEnumValue = win32api.RegEnumValue
        RegError = win32api.error
    except ImportError:
        log.info("Warning: Can't read registry to find the "
                 "necessary compiler setting\n"
                 "Make sure that Python modules winreg, "
                 "win32api or win32con are installed.")

if _can_read_reg:
    HKEYS = (hkey_mod.HKEY_USERS,
             hkey_mod.HKEY_CURRENT_USER,
             hkey_mod.HKEY_LOCAL_MACHINE,
             hkey_mod.HKEY_CLASSES_ROOT)

def read_keys(base, key):
    
    try:
        handle = RegOpenKeyEx(base, key)
    except RegError:
        return None
    L = []
    i = 0
    while True:
        try:
            k = RegEnumKey(handle, i)
        except RegError:
            break
        L.append(k)
        i += 1
    return L

def read_values(base, key):
    
    try:
        handle = RegOpenKeyEx(base, key)
    except RegError:
        return None
    d = {}
    i = 0
    while True:
        try:
            name, value, type = RegEnumValue(handle, i)
        except RegError:
            break
        name = name.lower()
        d[convert_mbcs(name)] = convert_mbcs(value)
        i += 1
    return d

def convert_mbcs(s):
    dec = getattr(s, "decode", None)
    if dec is not None:
        try:
            s = dec("mbcs")
        except UnicodeError:
            pass
    return s

class MacroExpander:
    def __init__(self, version):
        self.macros = {}
        self.load_macros(version)

    def set_macro(self, macro, path, key):
        for base in HKEYS:
            d = read_values(base, path)
            if d:
                self.macros["$(%s)" % macro] = d[key]
                break

    def load_macros(self, version):
        vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version
        self.set_macro("VCInstallDir", vsbase + r"\Setup\VC", "productdir")
        self.set_macro("VSInstallDir", vsbase + r"\Setup\VS", "productdir")
        net = r"Software\Microsoft\.NETFramework"
        self.set_macro("FrameworkDir", net, "installroot")
        try:
            if version > 7.0:
                self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1")
            else:
                self.set_macro("FrameworkSDKDir", net, "sdkinstallroot")
        except KeyError as exc: 
            raise DistutilsPlatformError(
            )

        p = r"Software\Microsoft\NET Framework Setup\Product"
        for base in HKEYS:
            try:
                h = RegOpenKeyEx(base, p)
            except RegError:
                continue
            key = RegEnumKey(h, 0)
            d = read_values(base, r"%s\%s" % (p, key))
            self.macros["$(FrameworkVersion)"] = d["version"]

    def sub(self, s):
        for k, v in self.macros.items():
            s = s.replace(k, v)
        return s

def get_build_version():
    
    prefix = "MSC v."
    i = sys.version.find(prefix)
    if i == -1:
        return 6
    i = i + len(prefix)
    s, rest = sys.version[i:].split(" ", 1)
    majorVersion = int(s[:-2]) - 6
    if majorVersion >= 13:
        
        majorVersion += 1
    minorVersion = int(s[2:3]) / 10.0
    
    if majorVersion == 6:
        minorVersion = 0
    if majorVersion >= 6:
        return majorVersion + minorVersion
    
    return None

def get_build_architecture():
    

    prefix = " bit ("
    i = sys.version.find(prefix)
    if i == -1:
        return "Intel"
    j = sys.version.find(")", i)
    return sys.version[i+len(prefix):j]

def normalize_and_reduce_paths(paths):
    
    
    reduced_paths = []
    for p in paths:
        np = os.path.normpath(p)
        
        if np not in reduced_paths:
            reduced_paths.append(np)
    return reduced_paths


class MSVCCompiler(CCompiler) :
    

    compiler_type = 'msvc'

    
    
    
    
    
    executables = {}

    
    _c_extensions = ['.c']
    _cpp_extensions = ['.cc', '.cpp', '.cxx']
    _rc_extensions = ['.rc']
    _mc_extensions = ['.mc']

    
    
    src_extensions = (_c_extensions + _cpp_extensions +
                      _rc_extensions + _mc_extensions)
    res_extension = '.res'
    obj_extension = '.obj'
    static_lib_extension = '.lib'
    shared_lib_extension = '.dll'
    static_lib_format = shared_lib_format = '%s%s'
    exe_extension = '.exe'

    def __init__(self, verbose=0, dry_run=0, force=0):
        CCompiler.__init__ (self, verbose, dry_run, force)
        self.__version = get_build_version()
        self.__arch = get_build_architecture()
        if self.__arch == "Intel":
            
            if self.__version >= 7:
                self.__root = r"Software\Microsoft\VisualStudio"
                self.__macros = MacroExpander(self.__version)
            else:
                self.__root = r"Software\Microsoft\Devstudio"
            self.__product = "Visual Studio version %s" % self.__version
        else:
            
            self.__product = "Microsoft SDK compiler %s" % (self.__version + 6)

        self.initialized = False


    

    

    def find_exe(self, exe):
        
        for p in self.__paths:
            fn = os.path.join(os.path.abspath(p), exe)
            if os.path.isfile(fn):
                return fn

        
        for p in os.environ['Path'].split(';'):
            fn = os.path.join(os.path.abspath(p),exe)
            if os.path.isfile(fn):
                return fn

        return exe

    def get_msvc_paths(self, path, platform='x86'):
        
        if not _can_read_reg:
            return []

        path = path + " dirs"
        if self.__version >= 7:
            key = (r"%s\%0.1f\VC\VC_OBJECTS_PLATFORM_INFO\Win32\Directories"
                   % (self.__root, self.__version))
        else:
            key = (r"%s\6.0\Build System\Components\Platforms"
                   r"\Win32 (%s)\Directories" % (self.__root, platform))

        for base in HKEYS:
            d = read_values(base, key)
            if d:
                if self.__version >= 7:
                    return self.__macros.sub(d[path]).split(";")
                else:
                    return d[path].split(";")
        
        
        if self.__version == 6:
            for base in HKEYS:
                if read_values(base, r"%s\6.0" % self.__root) is not None:
                    self.warn("It seems you have Visual Studio 6 installed, "
                        "but the expected registry settings are not present.\n"
                        "You must at least run the Visual Studio GUI once "
                        "so that these entries are created.")
                    break
        return []

    def set_path_env_var(self, name):
        

        if name == "lib":
            p = self.get_msvc_paths("library")
        else:
            p = self.get_msvc_paths(name)
        if p:
            os.environ[name] = ';'.join(p)


if get_build_version() >= 8.0:
    log.debug("Importing new compiler from distutils.msvc9compiler")
    OldMSVCCompiler = MSVCCompiler
    from distutils.msvc9compiler import MSVCCompiler
    
    from distutils.msvc9compiler import MacroExpander