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

2024-04-20 04:28:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: 方法字符串pybuild名称编译器compilersys
3条回答

这是Luper Rouch的答案的扩展版本,它对我在windows上使用mingw和msvc编译openmp扩展起到了作用。子类化build_ext之后,需要将其传递给cmdclass arg中的setup.py。通过子类化build_扩展而不是finalize_选项,您将拥有实际的编译器对象,因此您可以获得更详细的版本信息。最终,您可以根据每个编译器、每个扩展名设置编译器标志:

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 } )
#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() + '"'

可以对distutils.command.build_ext.build_ext命令进行子类化。

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

相关问题 更多 >