Python distutils,如何获得将要使用的编译器?

时间:2009-04-07 08:36:07

标签: python compiler-construction installation distutils

例如,我可以使用python setup.py build --compiler=msvcpython setup.py build --compiler=mingw32python setup.py build,在这种情况下,将使用默认编译器(例如,bcpp)。如何在setup.py中找到编译器名称(例如msvcmingw32bcpp)?

UPD。:我不需要默认的编译器,我需要使用实际的那个,这不一定是默认的。到目前为止,我还没有找到比解析sys.argv更好的方法来查看那里是否有--compiler...字符串。

6 个答案:

答案 0 :(得分:26)

这是Luper Rouch的扩展版本的答案,这对我来说是一个openmp扩展,可​​以在windows上使用mingw和msvc进行编译。在继承build_ext之后,您需要将它传递给cmdclass arg中的setup.py.通过继承build_extensions而不是finalize_options,您将拥有要查看的实际编译器对象,以便您可以获得更详细的版本信息。您最终可以在每个编译器的每个扩展基础上设置编译器标志:

from distutils.core import setup, Extension
from distutils.command.build_ext import build_ext
copt =  {'msvc': ['/openmp', '/Ox', '/fp:fast','/favor:INTEL64','/Og']  ,
     'mingw32' : ['-fopenmp','-O3','-ffast-math','-march=native']       }
lopt =  {'mingw32' : ['-fopenmp'] }

class build_ext_subclass( build_ext ):
    def build_extensions(self):
        c = self.compiler.compiler_type
        if copt.has_key(c):
           for e in self.extensions:
               e.extra_compile_args = copt[ c ]
        if lopt.has_key(c):
            for e in self.extensions:
                e.extra_link_args = lopt[ c ]
        build_ext.build_extensions(self)

mod = Extension('_wripaca',
            sources=['../wripaca_wrap.c', 
                     '../../src/wripaca.c'],
            include_dirs=['../../include']
            )

setup (name = 'wripaca',
   ext_modules = [mod],
   py_modules = ["wripaca"],
   cmdclass = {'build_ext': build_ext_subclass } )

答案 1 :(得分:7)

您可以继承distutils.command.build_ext.build_ext命令。

调用build_ext.finalize_options()方法后,编译器类型将作为字符串存储在self.compiler.compiler_type中(与传递给build_ext --compiler选项的方法相同,例如'mingw32','gcc'等......)。

答案 2 :(得分:2)

#This should work pretty good
def compilerName():
  import re
  import distutils.ccompiler
  comp = distutils.ccompiler.get_default_compiler()
  getnext = False

  for a in sys.argv[2:]:
    if getnext:
      comp = a
      getnext = False
      continue
    #separated by space
    if a == '--compiler'  or  re.search('^-[a-z]*c$', a):
      getnext = True
      continue
    #without space
    m = re.search('^--compiler=(.+)', a)
    if m == None:
      m = re.search('^-[a-z]*c(.+)', a)
    if m:
      comp = m.group(1)

  return comp


print "Using compiler " + '"' + compilerName() + '"'

答案 3 :(得分:0)

import distutils.ccompiler

compiler_name = distutils.ccompiler.get_default_compiler()

答案 4 :(得分:0)

import sys
sys.argv.extend(['--compiler', 'msvc'])

答案 5 :(得分:0)

class BuildWithDLLs(build):

    # On Windows, we install the git2.dll too.
    def _get_dlls(self):
        # return a list of of (FQ-in-name, relative-out-name) tuples.
        ret = []
        bld_ext = self.distribution.get_command_obj('build_ext')
        compiler_type = bld_ext.compiler.compiler_type

您可以使用self.distribution.get_command_obj('build_ext')来获取build_ext实例, 然后获取compiler_type