PageRenderTime 49ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/lib-python/2.7/distutils/command/build_ext.py

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