build_ext.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. """distutils.command.build_ext
  2. Implements the Distutils 'build_ext' command, for building extension
  3. modules (currently limited to C extensions, should accommodate C++
  4. extensions ASAP)."""
  5. import contextlib
  6. import os
  7. import re
  8. import sys
  9. from distutils.core import Command
  10. from distutils.errors import *
  11. from distutils.sysconfig import customize_compiler, get_python_version
  12. from distutils.sysconfig import get_config_h_filename
  13. from distutils.dep_util import newer_group
  14. from distutils.extension import Extension
  15. from distutils.util import get_platform
  16. from distutils import log
  17. from . import py37compat
  18. from site import USER_BASE
  19. # An extension name is just a dot-separated list of Python NAMEs (ie.
  20. # the same as a fully-qualified module name).
  21. extension_name_re = re.compile \
  22. (r'^[a-zA-Z_][a-zA-Z_0-9]*(\.[a-zA-Z_][a-zA-Z_0-9]*)*$')
  23. def show_compilers ():
  24. from distutils.ccompiler import show_compilers
  25. show_compilers()
  26. class build_ext(Command):
  27. description = "build C/C++ extensions (compile/link to build directory)"
  28. # XXX thoughts on how to deal with complex command-line options like
  29. # these, i.e. how to make it so fancy_getopt can suck them off the
  30. # command line and make it look like setup.py defined the appropriate
  31. # lists of tuples of what-have-you.
  32. # - each command needs a callback to process its command-line options
  33. # - Command.__init__() needs access to its share of the whole
  34. # command line (must ultimately come from
  35. # Distribution.parse_command_line())
  36. # - it then calls the current command class' option-parsing
  37. # callback to deal with weird options like -D, which have to
  38. # parse the option text and churn out some custom data
  39. # structure
  40. # - that data structure (in this case, a list of 2-tuples)
  41. # will then be present in the command object by the time
  42. # we get to finalize_options() (i.e. the constructor
  43. # takes care of both command-line and client options
  44. # in between initialize_options() and finalize_options())
  45. sep_by = " (separated by '%s')" % os.pathsep
  46. user_options = [
  47. ('build-lib=', 'b',
  48. "directory for compiled extension modules"),
  49. ('build-temp=', 't',
  50. "directory for temporary files (build by-products)"),
  51. ('plat-name=', 'p',
  52. "platform name to cross-compile for, if supported "
  53. "(default: %s)" % get_platform()),
  54. ('inplace', 'i',
  55. "ignore build-lib and put compiled extensions into the source " +
  56. "directory alongside your pure Python modules"),
  57. ('include-dirs=', 'I',
  58. "list of directories to search for header files" + sep_by),
  59. ('define=', 'D',
  60. "C preprocessor macros to define"),
  61. ('undef=', 'U',
  62. "C preprocessor macros to undefine"),
  63. ('libraries=', 'l',
  64. "external C libraries to link with"),
  65. ('library-dirs=', 'L',
  66. "directories to search for external C libraries" + sep_by),
  67. ('rpath=', 'R',
  68. "directories to search for shared C libraries at runtime"),
  69. ('link-objects=', 'O',
  70. "extra explicit link objects to include in the link"),
  71. ('debug', 'g',
  72. "compile/link with debugging information"),
  73. ('force', 'f',
  74. "forcibly build everything (ignore file timestamps)"),
  75. ('compiler=', 'c',
  76. "specify the compiler type"),
  77. ('parallel=', 'j',
  78. "number of parallel build jobs"),
  79. ('swig-cpp', None,
  80. "make SWIG create C++ files (default is C)"),
  81. ('swig-opts=', None,
  82. "list of SWIG command line options"),
  83. ('swig=', None,
  84. "path to the SWIG executable"),
  85. ('user', None,
  86. "add user include, library and rpath")
  87. ]
  88. boolean_options = ['inplace', 'debug', 'force', 'swig-cpp', 'user']
  89. help_options = [
  90. ('help-compiler', None,
  91. "list available compilers", show_compilers),
  92. ]
  93. def initialize_options(self):
  94. self.extensions = None
  95. self.build_lib = None
  96. self.plat_name = None
  97. self.build_temp = None
  98. self.inplace = 0
  99. self.package = None
  100. self.include_dirs = None
  101. self.define = None
  102. self.undef = None
  103. self.libraries = None
  104. self.library_dirs = None
  105. self.rpath = None
  106. self.link_objects = None
  107. self.debug = None
  108. self.force = None
  109. self.compiler = None
  110. self.swig = None
  111. self.swig_cpp = None
  112. self.swig_opts = None
  113. self.user = None
  114. self.parallel = None
  115. def finalize_options(self):
  116. from distutils import sysconfig
  117. self.set_undefined_options('build',
  118. ('build_lib', 'build_lib'),
  119. ('build_temp', 'build_temp'),
  120. ('compiler', 'compiler'),
  121. ('debug', 'debug'),
  122. ('force', 'force'),
  123. ('parallel', 'parallel'),
  124. ('plat_name', 'plat_name'),
  125. )
  126. if self.package is None:
  127. self.package = self.distribution.ext_package
  128. self.extensions = self.distribution.ext_modules
  129. # Make sure Python's include directories (for Python.h, pyconfig.h,
  130. # etc.) are in the include search path.
  131. py_include = sysconfig.get_python_inc()
  132. plat_py_include = sysconfig.get_python_inc(plat_specific=1)
  133. if self.include_dirs is None:
  134. self.include_dirs = self.distribution.include_dirs or []
  135. if isinstance(self.include_dirs, str):
  136. self.include_dirs = self.include_dirs.split(os.pathsep)
  137. # If in a virtualenv, add its include directory
  138. # Issue 16116
  139. if sys.exec_prefix != sys.base_exec_prefix:
  140. self.include_dirs.append(os.path.join(sys.exec_prefix, 'include'))
  141. # Put the Python "system" include dir at the end, so that
  142. # any local include dirs take precedence.
  143. self.include_dirs.extend(py_include.split(os.path.pathsep))
  144. if plat_py_include != py_include:
  145. self.include_dirs.extend(
  146. plat_py_include.split(os.path.pathsep))
  147. self.ensure_string_list('libraries')
  148. self.ensure_string_list('link_objects')
  149. # Life is easier if we're not forever checking for None, so
  150. # simplify these options to empty lists if unset
  151. if self.libraries is None:
  152. self.libraries = []
  153. if self.library_dirs is None:
  154. self.library_dirs = []
  155. elif isinstance(self.library_dirs, str):
  156. self.library_dirs = self.library_dirs.split(os.pathsep)
  157. if self.rpath is None:
  158. self.rpath = []
  159. elif isinstance(self.rpath, str):
  160. self.rpath = self.rpath.split(os.pathsep)
  161. # for extensions under windows use different directories
  162. # for Release and Debug builds.
  163. # also Python's library directory must be appended to library_dirs
  164. if os.name == 'nt':
  165. # the 'libs' directory is for binary installs - we assume that
  166. # must be the *native* platform. But we don't really support
  167. # cross-compiling via a binary install anyway, so we let it go.
  168. self.library_dirs.append(os.path.join(sys.exec_prefix, 'libs'))
  169. if sys.base_exec_prefix != sys.prefix: # Issue 16116
  170. self.library_dirs.append(os.path.join(sys.base_exec_prefix, 'libs'))
  171. if self.debug:
  172. self.build_temp = os.path.join(self.build_temp, "Debug")
  173. else:
  174. self.build_temp = os.path.join(self.build_temp, "Release")
  175. # Append the source distribution include and library directories,
  176. # this allows distutils on windows to work in the source tree
  177. self.include_dirs.append(os.path.dirname(get_config_h_filename()))
  178. _sys_home = getattr(sys, '_home', None)
  179. if _sys_home:
  180. self.library_dirs.append(_sys_home)
  181. # Use the .lib files for the correct architecture
  182. if self.plat_name == 'win32':
  183. suffix = 'win32'
  184. else:
  185. # win-amd64
  186. suffix = self.plat_name[4:]
  187. new_lib = os.path.join(sys.exec_prefix, 'PCbuild')
  188. if suffix:
  189. new_lib = os.path.join(new_lib, suffix)
  190. self.library_dirs.append(new_lib)
  191. # For extensions under Cygwin, Python's library directory must be
  192. # appended to library_dirs
  193. if sys.platform[:6] == 'cygwin':
  194. if not sysconfig.python_build:
  195. # building third party extensions
  196. self.library_dirs.append(os.path.join(sys.prefix, "lib",
  197. "python" + get_python_version(),
  198. "config"))
  199. else:
  200. # building python standard extensions
  201. self.library_dirs.append('.')
  202. # For building extensions with a shared Python library,
  203. # Python's library directory must be appended to library_dirs
  204. # See Issues: #1600860, #4366
  205. if (sysconfig.get_config_var('Py_ENABLE_SHARED')):
  206. if not sysconfig.python_build:
  207. # building third party extensions
  208. self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))
  209. else:
  210. # building python standard extensions
  211. self.library_dirs.append('.')
  212. # The argument parsing will result in self.define being a string, but
  213. # it has to be a list of 2-tuples. All the preprocessor symbols
  214. # specified by the 'define' option will be set to '1'. Multiple
  215. # symbols can be separated with commas.
  216. if self.define:
  217. defines = self.define.split(',')
  218. self.define = [(symbol, '1') for symbol in defines]
  219. # The option for macros to undefine is also a string from the
  220. # option parsing, but has to be a list. Multiple symbols can also
  221. # be separated with commas here.
  222. if self.undef:
  223. self.undef = self.undef.split(',')
  224. if self.swig_opts is None:
  225. self.swig_opts = []
  226. else:
  227. self.swig_opts = self.swig_opts.split(' ')
  228. # Finally add the user include and library directories if requested
  229. if self.user:
  230. user_include = os.path.join(USER_BASE, "include")
  231. user_lib = os.path.join(USER_BASE, "lib")
  232. if os.path.isdir(user_include):
  233. self.include_dirs.append(user_include)
  234. if os.path.isdir(user_lib):
  235. self.library_dirs.append(user_lib)
  236. self.rpath.append(user_lib)
  237. if isinstance(self.parallel, str):
  238. try:
  239. self.parallel = int(self.parallel)
  240. except ValueError:
  241. raise DistutilsOptionError("parallel should be an integer")
  242. def run(self):
  243. from distutils.ccompiler import new_compiler
  244. # 'self.extensions', as supplied by setup.py, is a list of
  245. # Extension instances. See the documentation for Extension (in
  246. # distutils.extension) for details.
  247. #
  248. # For backwards compatibility with Distutils 0.8.2 and earlier, we
  249. # also allow the 'extensions' list to be a list of tuples:
  250. # (ext_name, build_info)
  251. # where build_info is a dictionary containing everything that
  252. # Extension instances do except the name, with a few things being
  253. # differently named. We convert these 2-tuples to Extension
  254. # instances as needed.
  255. if not self.extensions:
  256. return
  257. # If we were asked to build any C/C++ libraries, make sure that the
  258. # directory where we put them is in the library search path for
  259. # linking extensions.
  260. if self.distribution.has_c_libraries():
  261. build_clib = self.get_finalized_command('build_clib')
  262. self.libraries.extend(build_clib.get_library_names() or [])
  263. self.library_dirs.append(build_clib.build_clib)
  264. # Setup the CCompiler object that we'll use to do all the
  265. # compiling and linking
  266. self.compiler = new_compiler(compiler=self.compiler,
  267. verbose=self.verbose,
  268. dry_run=self.dry_run,
  269. force=self.force)
  270. customize_compiler(self.compiler)
  271. # If we are cross-compiling, init the compiler now (if we are not
  272. # cross-compiling, init would not hurt, but people may rely on
  273. # late initialization of compiler even if they shouldn't...)
  274. if os.name == 'nt' and self.plat_name != get_platform():
  275. self.compiler.initialize(self.plat_name)
  276. # And make sure that any compile/link-related options (which might
  277. # come from the command-line or from the setup script) are set in
  278. # that CCompiler object -- that way, they automatically apply to
  279. # all compiling and linking done here.
  280. if self.include_dirs is not None:
  281. self.compiler.set_include_dirs(self.include_dirs)
  282. if self.define is not None:
  283. # 'define' option is a list of (name,value) tuples
  284. for (name, value) in self.define:
  285. self.compiler.define_macro(name, value)
  286. if self.undef is not None:
  287. for macro in self.undef:
  288. self.compiler.undefine_macro(macro)
  289. if self.libraries is not None:
  290. self.compiler.set_libraries(self.libraries)
  291. if self.library_dirs is not None:
  292. self.compiler.set_library_dirs(self.library_dirs)
  293. if self.rpath is not None:
  294. self.compiler.set_runtime_library_dirs(self.rpath)
  295. if self.link_objects is not None:
  296. self.compiler.set_link_objects(self.link_objects)
  297. # Now actually compile and link everything.
  298. self.build_extensions()
  299. def check_extensions_list(self, extensions):
  300. """Ensure that the list of extensions (presumably provided as a
  301. command option 'extensions') is valid, i.e. it is a list of
  302. Extension objects. We also support the old-style list of 2-tuples,
  303. where the tuples are (ext_name, build_info), which are converted to
  304. Extension instances here.
  305. Raise DistutilsSetupError if the structure is invalid anywhere;
  306. just returns otherwise.
  307. """
  308. if not isinstance(extensions, list):
  309. raise DistutilsSetupError(
  310. "'ext_modules' option must be a list of Extension instances")
  311. for i, ext in enumerate(extensions):
  312. if isinstance(ext, Extension):
  313. continue # OK! (assume type-checking done
  314. # by Extension constructor)
  315. if not isinstance(ext, tuple) or len(ext) != 2:
  316. raise DistutilsSetupError(
  317. "each element of 'ext_modules' option must be an "
  318. "Extension instance or 2-tuple")
  319. ext_name, build_info = ext
  320. log.warn("old-style (ext_name, build_info) tuple found in "
  321. "ext_modules for extension '%s' "
  322. "-- please convert to Extension instance", ext_name)
  323. if not (isinstance(ext_name, str) and
  324. extension_name_re.match(ext_name)):
  325. raise DistutilsSetupError(
  326. "first element of each tuple in 'ext_modules' "
  327. "must be the extension name (a string)")
  328. if not isinstance(build_info, dict):
  329. raise DistutilsSetupError(
  330. "second element of each tuple in 'ext_modules' "
  331. "must be a dictionary (build info)")
  332. # OK, the (ext_name, build_info) dict is type-safe: convert it
  333. # to an Extension instance.
  334. ext = Extension(ext_name, build_info['sources'])
  335. # Easy stuff: one-to-one mapping from dict elements to
  336. # instance attributes.
  337. for key in ('include_dirs', 'library_dirs', 'libraries',
  338. 'extra_objects', 'extra_compile_args',
  339. 'extra_link_args'):
  340. val = build_info.get(key)
  341. if val is not None:
  342. setattr(ext, key, val)
  343. # Medium-easy stuff: same syntax/semantics, different names.
  344. ext.runtime_library_dirs = build_info.get('rpath')
  345. if 'def_file' in build_info:
  346. log.warn("'def_file' element of build info dict "
  347. "no longer supported")
  348. # Non-trivial stuff: 'macros' split into 'define_macros'
  349. # and 'undef_macros'.
  350. macros = build_info.get('macros')
  351. if macros:
  352. ext.define_macros = []
  353. ext.undef_macros = []
  354. for macro in macros:
  355. if not (isinstance(macro, tuple) and len(macro) in (1, 2)):
  356. raise DistutilsSetupError(
  357. "'macros' element of build info dict "
  358. "must be 1- or 2-tuple")
  359. if len(macro) == 1:
  360. ext.undef_macros.append(macro[0])
  361. elif len(macro) == 2:
  362. ext.define_macros.append(macro)
  363. extensions[i] = ext
  364. def get_source_files(self):
  365. self.check_extensions_list(self.extensions)
  366. filenames = []
  367. # Wouldn't it be neat if we knew the names of header files too...
  368. for ext in self.extensions:
  369. filenames.extend(ext.sources)
  370. return filenames
  371. def get_outputs(self):
  372. # Sanity check the 'extensions' list -- can't assume this is being
  373. # done in the same run as a 'build_extensions()' call (in fact, we
  374. # can probably assume that it *isn't*!).
  375. self.check_extensions_list(self.extensions)
  376. # And build the list of output (built) filenames. Note that this
  377. # ignores the 'inplace' flag, and assumes everything goes in the
  378. # "build" tree.
  379. outputs = []
  380. for ext in self.extensions:
  381. outputs.append(self.get_ext_fullpath(ext.name))
  382. return outputs
  383. def build_extensions(self):
  384. # First, sanity-check the 'extensions' list
  385. self.check_extensions_list(self.extensions)
  386. if self.parallel:
  387. self._build_extensions_parallel()
  388. else:
  389. self._build_extensions_serial()
  390. def _build_extensions_parallel(self):
  391. workers = self.parallel
  392. if self.parallel is True:
  393. workers = os.cpu_count() # may return None
  394. try:
  395. from concurrent.futures import ThreadPoolExecutor
  396. except ImportError:
  397. workers = None
  398. if workers is None:
  399. self._build_extensions_serial()
  400. return
  401. with ThreadPoolExecutor(max_workers=workers) as executor:
  402. futures = [executor.submit(self.build_extension, ext)
  403. for ext in self.extensions]
  404. for ext, fut in zip(self.extensions, futures):
  405. with self._filter_build_errors(ext):
  406. fut.result()
  407. def _build_extensions_serial(self):
  408. for ext in self.extensions:
  409. with self._filter_build_errors(ext):
  410. self.build_extension(ext)
  411. @contextlib.contextmanager
  412. def _filter_build_errors(self, ext):
  413. try:
  414. yield
  415. except (CCompilerError, DistutilsError, CompileError) as e:
  416. if not ext.optional:
  417. raise
  418. self.warn('building extension "%s" failed: %s' %
  419. (ext.name, e))
  420. def build_extension(self, ext):
  421. sources = ext.sources
  422. if sources is None or not isinstance(sources, (list, tuple)):
  423. raise DistutilsSetupError(
  424. "in 'ext_modules' option (extension '%s'), "
  425. "'sources' must be present and must be "
  426. "a list of source filenames" % ext.name)
  427. # sort to make the resulting .so file build reproducible
  428. sources = sorted(sources)
  429. ext_path = self.get_ext_fullpath(ext.name)
  430. depends = sources + ext.depends
  431. if not (self.force or newer_group(depends, ext_path, 'newer')):
  432. log.debug("skipping '%s' extension (up-to-date)", ext.name)
  433. return
  434. else:
  435. log.info("building '%s' extension", ext.name)
  436. # First, scan the sources for SWIG definition files (.i), run
  437. # SWIG on 'em to create .c files, and modify the sources list
  438. # accordingly.
  439. sources = self.swig_sources(sources, ext)
  440. # Next, compile the source code to object files.
  441. # XXX not honouring 'define_macros' or 'undef_macros' -- the
  442. # CCompiler API needs to change to accommodate this, and I
  443. # want to do one thing at a time!
  444. # Two possible sources for extra compiler arguments:
  445. # - 'extra_compile_args' in Extension object
  446. # - CFLAGS environment variable (not particularly
  447. # elegant, but people seem to expect it and I
  448. # guess it's useful)
  449. # The environment variable should take precedence, and
  450. # any sensible compiler will give precedence to later
  451. # command line args. Hence we combine them in order:
  452. extra_args = ext.extra_compile_args or []
  453. macros = ext.define_macros[:]
  454. for undef in ext.undef_macros:
  455. macros.append((undef,))
  456. objects = self.compiler.compile(sources,
  457. output_dir=self.build_temp,
  458. macros=macros,
  459. include_dirs=ext.include_dirs,
  460. debug=self.debug,
  461. extra_postargs=extra_args,
  462. depends=ext.depends)
  463. # XXX outdated variable, kept here in case third-part code
  464. # needs it.
  465. self._built_objects = objects[:]
  466. # Now link the object files together into a "shared object" --
  467. # of course, first we have to figure out all the other things
  468. # that go into the mix.
  469. if ext.extra_objects:
  470. objects.extend(ext.extra_objects)
  471. extra_args = ext.extra_link_args or []
  472. # Detect target language, if not provided
  473. language = ext.language or self.compiler.detect_language(sources)
  474. self.compiler.link_shared_object(
  475. objects, ext_path,
  476. libraries=self.get_libraries(ext),
  477. library_dirs=ext.library_dirs,
  478. runtime_library_dirs=ext.runtime_library_dirs,
  479. extra_postargs=extra_args,
  480. export_symbols=self.get_export_symbols(ext),
  481. debug=self.debug,
  482. build_temp=self.build_temp,
  483. target_lang=language)
  484. def swig_sources(self, sources, extension):
  485. """Walk the list of source files in 'sources', looking for SWIG
  486. interface (.i) files. Run SWIG on all that are found, and
  487. return a modified 'sources' list with SWIG source files replaced
  488. by the generated C (or C++) files.
  489. """
  490. new_sources = []
  491. swig_sources = []
  492. swig_targets = {}
  493. # XXX this drops generated C/C++ files into the source tree, which
  494. # is fine for developers who want to distribute the generated
  495. # source -- but there should be an option to put SWIG output in
  496. # the temp dir.
  497. if self.swig_cpp:
  498. log.warn("--swig-cpp is deprecated - use --swig-opts=-c++")
  499. if self.swig_cpp or ('-c++' in self.swig_opts) or \
  500. ('-c++' in extension.swig_opts):
  501. target_ext = '.cpp'
  502. else:
  503. target_ext = '.c'
  504. for source in sources:
  505. (base, ext) = os.path.splitext(source)
  506. if ext == ".i": # SWIG interface file
  507. new_sources.append(base + '_wrap' + target_ext)
  508. swig_sources.append(source)
  509. swig_targets[source] = new_sources[-1]
  510. else:
  511. new_sources.append(source)
  512. if not swig_sources:
  513. return new_sources
  514. swig = self.swig or self.find_swig()
  515. swig_cmd = [swig, "-python"]
  516. swig_cmd.extend(self.swig_opts)
  517. if self.swig_cpp:
  518. swig_cmd.append("-c++")
  519. # Do not override commandline arguments
  520. if not self.swig_opts:
  521. for o in extension.swig_opts:
  522. swig_cmd.append(o)
  523. for source in swig_sources:
  524. target = swig_targets[source]
  525. log.info("swigging %s to %s", source, target)
  526. self.spawn(swig_cmd + ["-o", target, source])
  527. return new_sources
  528. def find_swig(self):
  529. """Return the name of the SWIG executable. On Unix, this is
  530. just "swig" -- it should be in the PATH. Tries a bit harder on
  531. Windows.
  532. """
  533. if os.name == "posix":
  534. return "swig"
  535. elif os.name == "nt":
  536. # Look for SWIG in its standard installation directory on
  537. # Windows (or so I presume!). If we find it there, great;
  538. # if not, act like Unix and assume it's in the PATH.
  539. for vers in ("1.3", "1.2", "1.1"):
  540. fn = os.path.join("c:\\swig%s" % vers, "swig.exe")
  541. if os.path.isfile(fn):
  542. return fn
  543. else:
  544. return "swig.exe"
  545. else:
  546. raise DistutilsPlatformError(
  547. "I don't know how to find (much less run) SWIG "
  548. "on platform '%s'" % os.name)
  549. # -- Name generators -----------------------------------------------
  550. # (extension names, filenames, whatever)
  551. def get_ext_fullpath(self, ext_name):
  552. """Returns the path of the filename for a given extension.
  553. The file is located in `build_lib` or directly in the package
  554. (inplace option).
  555. """
  556. fullname = self.get_ext_fullname(ext_name)
  557. modpath = fullname.split('.')
  558. filename = self.get_ext_filename(modpath[-1])
  559. if not self.inplace:
  560. # no further work needed
  561. # returning :
  562. # build_dir/package/path/filename
  563. filename = os.path.join(*modpath[:-1]+[filename])
  564. return os.path.join(self.build_lib, filename)
  565. # the inplace option requires to find the package directory
  566. # using the build_py command for that
  567. package = '.'.join(modpath[0:-1])
  568. build_py = self.get_finalized_command('build_py')
  569. package_dir = os.path.abspath(build_py.get_package_dir(package))
  570. # returning
  571. # package_dir/filename
  572. return os.path.join(package_dir, filename)
  573. def get_ext_fullname(self, ext_name):
  574. """Returns the fullname of a given extension name.
  575. Adds the `package.` prefix"""
  576. if self.package is None:
  577. return ext_name
  578. else:
  579. return self.package + '.' + ext_name
  580. def get_ext_filename(self, ext_name):
  581. r"""Convert the name of an extension (eg. "foo.bar") into the name
  582. of the file from which it will be loaded (eg. "foo/bar.so", or
  583. "foo\bar.pyd").
  584. """
  585. from distutils.sysconfig import get_config_var
  586. ext_path = ext_name.split('.')
  587. ext_suffix = get_config_var('EXT_SUFFIX')
  588. return os.path.join(*ext_path) + ext_suffix
  589. def get_export_symbols(self, ext):
  590. """Return the list of symbols that a shared extension has to
  591. export. This either uses 'ext.export_symbols' or, if it's not
  592. provided, "PyInit_" + module_name. Only relevant on Windows, where
  593. the .pyd file (DLL) must export the module "PyInit_" function.
  594. """
  595. name = ext.name.split('.')[-1]
  596. try:
  597. # Unicode module name support as defined in PEP-489
  598. # https://www.python.org/dev/peps/pep-0489/#export-hook-name
  599. name.encode('ascii')
  600. except UnicodeEncodeError:
  601. suffix = 'U_' + name.encode('punycode').replace(b'-', b'_').decode('ascii')
  602. else:
  603. suffix = "_" + name
  604. initfunc_name = "PyInit" + suffix
  605. if initfunc_name not in ext.export_symbols:
  606. ext.export_symbols.append(initfunc_name)
  607. return ext.export_symbols
  608. def get_libraries(self, ext):
  609. """Return the list of libraries to link against when building a
  610. shared extension. On most platforms, this is just 'ext.libraries';
  611. on Windows, we add the Python library (eg. python20.dll).
  612. """
  613. # The python library is always needed on Windows. For MSVC, this
  614. # is redundant, since the library is mentioned in a pragma in
  615. # pyconfig.h that MSVC groks. The other Windows compilers all seem
  616. # to need it mentioned explicitly, though, so that's what we do.
  617. # Append '_d' to the python import library on debug builds.
  618. if sys.platform == "win32":
  619. from distutils._msvccompiler import MSVCCompiler
  620. if not isinstance(self.compiler, MSVCCompiler):
  621. template = "python%d%d"
  622. if self.debug:
  623. template = template + '_d'
  624. pythonlib = (template %
  625. (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
  626. # don't extend ext.libraries, it may be shared with other
  627. # extensions, it is a reference to the original list
  628. return ext.libraries + [pythonlib]
  629. else:
  630. # On Android only the main executable and LD_PRELOADs are considered
  631. # to be RTLD_GLOBAL, all the dependencies of the main executable
  632. # remain RTLD_LOCAL and so the shared libraries must be linked with
  633. # libpython when python is built with a shared python library (issue
  634. # bpo-21536).
  635. # On Cygwin (and if required, other POSIX-like platforms based on
  636. # Windows like MinGW) it is simply necessary that all symbols in
  637. # shared libraries are resolved at link time.
  638. from distutils.sysconfig import get_config_var
  639. link_libpython = False
  640. if get_config_var('Py_ENABLE_SHARED'):
  641. # A native build on an Android device or on Cygwin
  642. if hasattr(sys, 'getandroidapilevel'):
  643. link_libpython = True
  644. elif sys.platform == 'cygwin':
  645. link_libpython = True
  646. elif '_PYTHON_HOST_PLATFORM' in os.environ:
  647. # We are cross-compiling for one of the relevant platforms
  648. if get_config_var('ANDROID_API_LEVEL') != 0:
  649. link_libpython = True
  650. elif get_config_var('MACHDEP') == 'cygwin':
  651. link_libpython = True
  652. if link_libpython:
  653. ldversion = get_config_var('LDVERSION')
  654. return ext.libraries + ['python' + ldversion]
  655. return ext.libraries + py37compat.pythonlib()