build_ext.py 31 KB

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