获取distutils传递给编译器的命令

11

假设我有这段Python代码在setup.py脚本中来构建一个C扩展:

from distutils.core import setup, Extension

module1 = Extension('demo', sources = ['demo.c'])

setup (name = 'PackageName',
       version = '1.0',
       description = 'This is a demo package',
       ext_modules = [module1])

很容易。现在我使用这行代码调用setup.py脚本:

C:/> python setup.py build_ext --compiler=mingw32

好的,但问题是什么?

当distutils调用mingw32并将所有必要且与操作系统无关的标志和选项传递给它时,它如何找出这些标志?

distutils在哪里存储与每个平台相关的命令,我怎样才能访问它们?


1
"Python distutils, how to get a compiler that is going to be used?" 的最佳答案还介绍了通过扩展 distutils.command.build_ext.build_ext 类来添加编译器特定的选项。 假定默认的命令行参数也存储在同一类中的某个地方,尽管我没有在该答案中特别提到它们。 - Kevin J. Chase
1个回答

10

这不是一个简单的选项集,但您可以看到它是如何工作的。在您的Python源目录中查找此文件

distutils/ccompiler.py
在那个文件中,每个编译器都有像这样的条目。
# Map compiler types to (module_name, class_name) pairs -- ie. where to
# find the code that implements an interface to this compiler.  (The module
# is assumed to be in the 'distutils' package.)
compiler_class = { 'unix':    ('unixccompiler', 'UnixCCompiler',
                               "standard UNIX-style compiler"),
                   'msvc':    ('msvccompiler', 'MSVCCompiler',
                               "Microsoft Visual C++"),
                   'cygwin':  ('cygwinccompiler', 'CygwinCCompiler',
                               "Cygwin port of GNU C Compiler for Win32"),
                   'mingw32': ('cygwinccompiler', 'Mingw32CCompiler',
                               "Mingw32 port of GNU C Compiler for Win32"),
                   'bcpp':    ('bcppcompiler', 'BCPPCompiler',
                               "Borland C++ Compiler"),
                   'emx':     ('emxccompiler', 'EMXCCompiler',
                               "EMX port of GNU C Compiler for OS/2"),
                 }    

您可以在以下位置找到您需要的代码

distutils/cygwinccompiler.py
如果您编辑setup.py脚本并添加此行代码
from distutils.core import setup,Extension
from distutils.cygwinccompiler import Mingw32CCompiler
from pprint import pprint

module1 = Extension('demo', sources = ['demo.c'])

m32 = Mingw32CCompiler()
pprint (vars(m32))


setup (name = 'PackageName',
   version = '1.0',
   description = 'This is a demo package',
   ext_modules = [module1])

你可以看到相当多的可用选项...

{'archiver': ['ar', '-cr'],
 'compiler': ['gcc', '-O', '-Wall'],
 'compiler_cxx': ['g++', '-O', '-Wall'],
 'compiler_so': ['gcc', '-mdll', '-O', '-Wall'],
 'dll_libraries': None,
 'dllwrap_version': None,
 'dry_run': 0,
 'force': 0,
 'gcc_version': LooseVersion ('4.2.1'),
 'include_dirs': [],
 'ld_version': None,
 'libraries': [],
 'library_dirs': [],
 'linker_dll': 'dllwrap',
 'linker_exe': ['gcc'],
 'linker_so': ['dllwrap', '-mdll', '-static'],
 'macros': [],
 'objects': [],
 'output_dir': None,
 'preprocessor': None,
 'ranlib': ['ranlib'],
 'runtime_library_dirs': [],
 'verbose': 0}

要访问每个选项,您可以按以下方式使用它们...

print m32.compile
['gcc', '-O', '-Wall']

没有简单的一组标志。许多标志在运行时配置,上面的代码显示了您要查看的位置以查看它们是如何生成的等信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接