home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / BUILD_EXT.PY < prev    next >
Encoding:
Python Source  |  2000-09-30  |  23.3 KB  |  581 lines

  1. """distutils.command.build_ext
  2.  
  3. Implements the Distutils 'build_ext' command, for building extension
  4. modules (currently limited to C extensions, should accommodate C++
  5. extensions ASAP)."""
  6.  
  7. # created 1999/08/09, Greg Ward
  8.  
  9. __revision__ = "$Id: build_ext.py,v 1.68 2000/09/30 18:27:54 gward Exp $"
  10.  
  11. import sys, os, string, re
  12. from types import *
  13. from distutils.core import Command
  14. from distutils.errors import *
  15. from distutils.sysconfig import customize_compiler
  16. from distutils.dep_util import newer_group
  17. from distutils.extension import Extension
  18.  
  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.  
  24.  
  25. def show_compilers ():
  26.     from distutils.ccompiler import show_compilers
  27.     show_compilers()
  28.  
  29.  
  30. class build_ext (Command):
  31.     
  32.     description = "build C/C++ extensions (compile/link to build directory)"
  33.  
  34.     # XXX thoughts on how to deal with complex command-line options like
  35.     # these, i.e. how to make it so fancy_getopt can suck them off the
  36.     # command line and make it look like setup.py defined the appropriate
  37.     # lists of tuples of what-have-you.
  38.     #   - each command needs a callback to process its command-line options
  39.     #   - Command.__init__() needs access to its share of the whole
  40.     #     command line (must ultimately come from
  41.     #     Distribution.parse_command_line())
  42.     #   - it then calls the current command class' option-parsing
  43.     #     callback to deal with weird options like -D, which have to
  44.     #     parse the option text and churn out some custom data
  45.     #     structure
  46.     #   - that data structure (in this case, a list of 2-tuples)
  47.     #     will then be present in the command object by the time
  48.     #     we get to finalize_options() (i.e. the constructor
  49.     #     takes care of both command-line and client options
  50.     #     in between initialize_options() and finalize_options())
  51.  
  52.     sep_by = " (separated by '%s')" % os.pathsep
  53.     user_options = [
  54.         ('build-lib=', 'b',
  55.          "directory for compiled extension modules"),
  56.         ('build-temp=', 't',
  57.          "directory for temporary files (build by-products)"),
  58.         ('inplace', 'i',
  59.          "ignore build-lib and put compiled extensions into the source " +
  60.          "directory alongside your pure Python modules"),
  61.         ('include-dirs=', 'I',
  62.          "list of directories to search for header files" + sep_by),
  63.         ('define=', 'D',
  64.          "C preprocessor macros to define"),
  65.         ('undef=', 'U',
  66.          "C preprocessor macros to undefine"),
  67.         ('libraries=', 'l',
  68.          "external C libraries to link with"),
  69.         ('library-dirs=', 'L',
  70.          "directories to search for external C libraries" + sep_by),
  71.         ('rpath=', 'R',
  72.          "directories to search for shared C libraries at runtime"),
  73.         ('link-objects=', 'O',
  74.          "extra explicit link objects to include in the link"),
  75.         ('debug', 'g',
  76.          "compile/link with debugging information"),
  77.         ('force', 'f',
  78.          "forcibly build everything (ignore file timestamps)"),
  79.         ('compiler=', 'c',
  80.          "specify the compiler type"),
  81.         ('swig-cpp', None,
  82.          "make SWIG create C++ files (default is C)"),
  83.         ]
  84.  
  85.     boolean_options = ['inplace', 'debug', 'force', 'swig-cpp']
  86.  
  87.     help_options = [
  88.         ('help-compiler', None,
  89.          "list available compilers", show_compilers),
  90.         ]
  91.  
  92.     def initialize_options (self):
  93.         self.extensions = None
  94.         self.build_lib = None
  95.         self.build_temp = None
  96.         self.inplace = 0
  97.         self.package = None
  98.  
  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_cpp = None
  110.  
  111.  
  112.     def finalize_options (self):
  113.         from distutils import sysconfig
  114.  
  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.  
  122.         if self.package is None:
  123.             self.package = self.distribution.ext_package
  124.  
  125.         self.extensions = self.distribution.ext_modules
  126.         
  127.  
  128.         # Make sure Python's include directories (for Python.h, config.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 type(self.include_dirs) is StringType:
  135.             self.include_dirs = string.split(self.include_dirs, os.pathsep)
  136.  
  137.         # Put the Python "system" include dir at the end, so that
  138.         # any local include dirs take precedence.
  139.         self.include_dirs.append(py_include)
  140.         if plat_py_include != py_include:
  141.             self.include_dirs.append(plat_py_include)
  142.  
  143.         if type(self.libraries) is StringType:
  144.             self.libraries = [self.libraries]
  145.  
  146.         # Life is easier if we're not forever checking for None, so
  147.         # simplify these options to empty lists if unset
  148.         if self.libraries is None:
  149.             self.libraries = []
  150.         if self.library_dirs is None:
  151.             self.library_dirs = []
  152.         if self.rpath is None:
  153.             self.rpath = []
  154.  
  155.         # for extensions under windows use different directories
  156.         # for Release and Debug builds.
  157.         # also Python's library directory must be appended to library_dirs
  158.         if os.name == 'nt':
  159.             self.library_dirs.append(os.path.join(sys.exec_prefix, 'libs'))
  160.             if self.debug:
  161.                 self.build_temp = os.path.join(self.build_temp, "Debug")
  162.             else:
  163.                 self.build_temp = os.path.join(self.build_temp, "Release")
  164.     # finalize_options ()
  165.     
  166.  
  167.     def run (self):
  168.  
  169.         from distutils.ccompiler import new_compiler
  170.  
  171.         # 'self.extensions', as supplied by setup.py, is a list of
  172.         # Extension instances.  See the documentation for Extension (in
  173.         # distutils.extension) for details.
  174.         # 
  175.         # For backwards compatibility with Distutils 0.8.2 and earlier, we
  176.         # also allow the 'extensions' list to be a list of tuples:
  177.         #    (ext_name, build_info)
  178.         # where build_info is a dictionary containing everything that
  179.         # Extension instances do except the name, with a few things being
  180.         # differently named.  We convert these 2-tuples to Extension
  181.         # instances as needed.
  182.  
  183.         if not self.extensions:
  184.             return
  185.  
  186.         # If we were asked to build any C/C++ libraries, make sure that the
  187.         # directory where we put them is in the library search path for
  188.         # linking extensions.
  189.         if self.distribution.has_c_libraries():
  190.             build_clib = self.get_finalized_command('build_clib')
  191.             self.libraries.extend(build_clib.get_library_names() or [])
  192.             self.library_dirs.append(build_clib.build_clib)
  193.  
  194.         # Setup the CCompiler object that we'll use to do all the
  195.         # compiling and linking
  196.         self.compiler = new_compiler(compiler=self.compiler,
  197.                                      verbose=self.verbose,
  198.                                      dry_run=self.dry_run,
  199.                                      force=self.force)
  200.         customize_compiler(self.compiler)
  201.  
  202.         # And make sure that any compile/link-related options (which might
  203.         # come from the command-line or from the setup script) are set in
  204.         # that CCompiler object -- that way, they automatically apply to
  205.         # all compiling and linking done here.
  206.         if self.include_dirs is not None:
  207.             self.compiler.set_include_dirs(self.include_dirs)
  208.         if self.define is not None:
  209.             # 'define' option is a list of (name,value) tuples
  210.             for (name,value) in self.define:
  211.                 self.compiler.define_macro(name, value)
  212.         if self.undef is not None:
  213.             for macro in self.undef:
  214.                 self.compiler.undefine_macro(macro)
  215.         if self.libraries is not None:
  216.             self.compiler.set_libraries(self.libraries)
  217.         if self.library_dirs is not None:
  218.             self.compiler.set_library_dirs(self.library_dirs)
  219.         if self.rpath is not None:
  220.             self.compiler.set_runtime_library_dirs(self.rpath)
  221.         if self.link_objects is not None:
  222.             self.compiler.set_link_objects(self.link_objects)
  223.  
  224.         # Now actually compile and link everything.
  225.         self.build_extensions()
  226.  
  227.     # run ()
  228.  
  229.  
  230.     def check_extensions_list (self, extensions):
  231.         """Ensure that the list of extensions (presumably provided as a
  232.         command option 'extensions') is valid, i.e. it is a list of
  233.         Extension objects.  We also support the old-style list of 2-tuples,
  234.         where the tuples are (ext_name, build_info), which are converted to
  235.         Extension instances here.
  236.  
  237.         Raise DistutilsSetupError if the structure is invalid anywhere;
  238.         just returns otherwise.
  239.         """
  240.         if type(extensions) is not ListType:
  241.             raise DistutilsSetupError, \
  242.                   "'ext_modules' option must be a list of Extension instances"
  243.         
  244.         for i in range(len(extensions)):
  245.             ext = extensions[i]
  246.             if isinstance(ext, Extension):
  247.                 continue                # OK! (assume type-checking done
  248.                                         # by Extension constructor)
  249.  
  250.             (ext_name, build_info) = ext
  251.             self.warn(("old-style (ext_name, build_info) tuple found in "
  252.                        "ext_modules for extension '%s'" 
  253.                        "-- please convert to Extension instance" % ext_name))
  254.             if type(ext) is not TupleType and len(ext) != 2:
  255.                 raise DistutilsSetupError, \
  256.                       ("each element of 'ext_modules' option must be an "
  257.                        "Extension instance or 2-tuple")
  258.  
  259.             if not (type(ext_name) is StringType and
  260.                     extension_name_re.match(ext_name)):
  261.                 raise DistutilsSetupError, \
  262.                       ("first element of each tuple in 'ext_modules' "
  263.                        "must be the extension name (a string)")
  264.  
  265.             if type(build_info) is not DictionaryType:
  266.                 raise DistutilsSetupError, \
  267.                       ("second element of each tuple in 'ext_modules' "
  268.                        "must be a dictionary (build info)")
  269.  
  270.             # OK, the (ext_name, build_info) dict is type-safe: convert it
  271.             # to an Extension instance.
  272.             ext = Extension(ext_name, build_info['sources'])
  273.  
  274.             # Easy stuff: one-to-one mapping from dict elements to
  275.             # instance attributes.
  276.             for key in ('include_dirs',
  277.                         'library_dirs',
  278.                         'libraries',
  279.                         'extra_objects',
  280.                         'extra_compile_args',
  281.                         'extra_link_args'):
  282.                 val = build_info.get(key)
  283.                 if val is not None:
  284.                     setattr(ext, key, val)
  285.  
  286.             # Medium-easy stuff: same syntax/semantics, different names.
  287.             ext.runtime_library_dirs = build_info.get('rpath')
  288.             if build_info.has_key('def_file'):
  289.                 self.warn("'def_file' element of build info dict "
  290.                           "no longer supported")
  291.  
  292.             # Non-trivial stuff: 'macros' split into 'define_macros'
  293.             # and 'undef_macros'.
  294.             macros = build_info.get('macros')
  295.             if macros:
  296.                 ext.define_macros = []
  297.                 ext.undef_macros = []
  298.                 for macro in macros:
  299.                     if not (type(macro) is TupleType and
  300.                             1 <= len(macro) <= 2):
  301.                         raise DistutilsSetupError, \
  302.                               ("'macros' element of build info dict "
  303.                                "must be 1- or 2-tuple")
  304.                     if len(macro) == 1:
  305.                         ext.undef_macros.append(macro[0])
  306.                     elif len(macro) == 2:
  307.                         ext.define_macros.append(macro)
  308.  
  309.             extensions[i] = ext
  310.  
  311.         # for extensions
  312.  
  313.     # check_extensions_list ()
  314.  
  315.  
  316.     def get_source_files (self):
  317.         self.check_extensions_list(self.extensions)
  318.         filenames = []
  319.  
  320.         # Wouldn't it be neat if we knew the names of header files too...
  321.         for ext in self.extensions:
  322.             filenames.extend(ext.sources)
  323.  
  324.         return filenames
  325.  
  326.  
  327.     def get_outputs (self):
  328.  
  329.         # Sanity check the 'extensions' list -- can't assume this is being
  330.         # done in the same run as a 'build_extensions()' call (in fact, we
  331.         # can probably assume that it *isn't*!).
  332.         self.check_extensions_list(self.extensions)
  333.  
  334.         # And build the list of output (built) filenames.  Note that this
  335.         # ignores the 'inplace' flag, and assumes everything goes in the
  336.         # "build" tree.
  337.         outputs = []
  338.         for ext in self.extensions:
  339.             fullname = self.get_ext_fullname(ext.name)
  340.             outputs.append(os.path.join(self.build_lib,
  341.                                         self.get_ext_filename(fullname)))
  342.         return outputs
  343.  
  344.     # get_outputs ()
  345.  
  346.  
  347.     def build_extensions (self):
  348.  
  349.         # First, sanity-check the 'extensions' list
  350.         self.check_extensions_list(self.extensions)
  351.  
  352.         for ext in self.extensions:
  353.             sources = ext.sources
  354.             if sources is None or type(sources) not in (ListType, TupleType):
  355.                 raise DistutilsSetupError, \
  356.                       ("in 'ext_modules' option (extension '%s'), " +
  357.                        "'sources' must be present and must be " +
  358.                        "a list of source filenames") % ext.name
  359.             sources = list(sources)
  360.  
  361.             fullname = self.get_ext_fullname(ext.name)
  362.             if self.inplace:
  363.                 # ignore build-lib -- put the compiled extension into
  364.                 # the source tree along with pure Python modules
  365.  
  366.                 modpath = string.split(fullname, '.')
  367.                 package = string.join(modpath[0:-1], '.')
  368.                 base = modpath[-1]
  369.  
  370.                 build_py = self.get_finalized_command('build_py')
  371.                 package_dir = build_py.get_package_dir(package)
  372.                 ext_filename = os.path.join(package_dir,
  373.                                             self.get_ext_filename(base))
  374.             else:
  375.                 ext_filename = os.path.join(self.build_lib,
  376.                                             self.get_ext_filename(fullname))
  377.  
  378.             if not (self.force or newer_group(sources, ext_filename, 'newer')):
  379.                 self.announce("skipping '%s' extension (up-to-date)" %
  380.                               ext.name)
  381.                 continue # 'for' loop over all extensions
  382.             else:
  383.                 self.announce("building '%s' extension" % ext.name)
  384.  
  385.             # First, scan the sources for SWIG definition files (.i), run
  386.             # SWIG on 'em to create .c files, and modify the sources list
  387.             # accordingly.
  388.             sources = self.swig_sources(sources)
  389.  
  390.             # Next, compile the source code to object files.
  391.  
  392.             # XXX not honouring 'define_macros' or 'undef_macros' -- the
  393.             # CCompiler API needs to change to accommodate this, and I
  394.             # want to do one thing at a time!
  395.  
  396.             # Two possible sources for extra compiler arguments:
  397.             #   - 'extra_compile_args' in Extension object
  398.             #   - CFLAGS environment variable (not particularly
  399.             #     elegant, but people seem to expect it and I
  400.             #     guess it's useful)
  401.             # The environment variable should take precedence, and
  402.             # any sensible compiler will give precedence to later
  403.             # command line args.  Hence we combine them in order:
  404.             extra_args = ext.extra_compile_args or []
  405.  
  406.             macros = ext.define_macros[:]
  407.             for undef in ext.undef_macros:
  408.                 macros.append((undef,))
  409.  
  410.             # XXX and if we support CFLAGS, why not CC (compiler
  411.             # executable), CPPFLAGS (pre-processor options), and LDFLAGS
  412.             # (linker options) too?
  413.             # XXX should we use shlex to properly parse CFLAGS?
  414.  
  415.             if os.environ.has_key('CFLAGS'):
  416.                 extra_args.extend(string.split(os.environ['CFLAGS']))
  417.                 
  418.             objects = self.compiler.compile(sources,
  419.                                             output_dir=self.build_temp,
  420.                                             macros=macros,
  421.                                             include_dirs=ext.include_dirs,
  422.                                             debug=self.debug,
  423.                                             extra_postargs=extra_args)
  424.  
  425.             # Now link the object files together into a "shared object" --
  426.             # of course, first we have to figure out all the other things
  427.             # that go into the mix.
  428.             if ext.extra_objects:
  429.                 objects.extend(ext.extra_objects)
  430.             extra_args = ext.extra_link_args or []
  431.  
  432.  
  433.             self.compiler.link_shared_object(
  434.                 objects, ext_filename, 
  435.                 libraries=self.get_libraries(ext),
  436.                 library_dirs=ext.library_dirs,
  437.                 runtime_library_dirs=ext.runtime_library_dirs,
  438.                 extra_postargs=extra_args,
  439.                 export_symbols=self.get_export_symbols(ext), 
  440.                 debug=self.debug,
  441.                 build_temp=self.build_temp)
  442.  
  443.     # build_extensions ()
  444.  
  445.  
  446.     def swig_sources (self, sources):
  447.  
  448.         """Walk the list of source files in 'sources', looking for SWIG
  449.         interface (.i) files.  Run SWIG on all that are found, and
  450.         return a modified 'sources' list with SWIG source files replaced
  451.         by the generated C (or C++) files.
  452.         """
  453.  
  454.         new_sources = []
  455.         swig_sources = []
  456.         swig_targets = {}
  457.  
  458.         # XXX this drops generated C/C++ files into the source tree, which
  459.         # is fine for developers who want to distribute the generated
  460.         # source -- but there should be an option to put SWIG output in
  461.         # the temp dir.
  462.  
  463.         if self.swig_cpp:
  464.             target_ext = '.cpp'
  465.         else:
  466.             target_ext = '.c'
  467.  
  468.         for source in sources:
  469.             (base, ext) = os.path.splitext(source)
  470.             if ext == ".i":             # SWIG interface file
  471.                 new_sources.append(base + target_ext)
  472.                 swig_sources.append(source)
  473.                 swig_targets[source] = new_sources[-1]
  474.             else:
  475.                 new_sources.append(source)
  476.  
  477.         if not swig_sources:
  478.             return new_sources
  479.  
  480.         swig = self.find_swig()
  481.         swig_cmd = [swig, "-python", "-dnone", "-ISWIG"]
  482.         if self.swig_cpp:
  483.             swig_cmd.append("-c++")
  484.  
  485.         for source in swig_sources:
  486.             target = swig_targets[source]
  487.             self.announce("swigging %s to %s" % (source, target))
  488.             self.spawn(swig_cmd + ["-o", target, source])
  489.  
  490.         return new_sources
  491.  
  492.     # swig_sources ()
  493.  
  494.     def find_swig (self):
  495.         """Return the name of the SWIG executable.  On Unix, this is
  496.         just "swig" -- it should be in the PATH.  Tries a bit harder on
  497.         Windows.
  498.         """
  499.  
  500.         if os.name == "posix":
  501.             return "swig"
  502.         elif os.name == "nt":
  503.  
  504.             # Look for SWIG in its standard installation directory on
  505.             # Windows (or so I presume!).  If we find it there, great;
  506.             # if not, act like Unix and assume it's in the PATH.
  507.             for vers in ("1.3", "1.2", "1.1"):
  508.                 fn = os.path.join("c:\\swig%s" % vers, "swig.exe")
  509.                 if os.path.isfile(fn):
  510.                     return fn
  511.             else:
  512.                 return "swig.exe"
  513.  
  514.         else:
  515.             raise DistutilsPlatformError, \
  516.                   ("I don't know how to find (much less run) SWIG "
  517.                    "on platform '%s'") % os.name
  518.  
  519.     # find_swig ()
  520.     
  521.     # -- Name generators -----------------------------------------------
  522.     # (extension names, filenames, whatever)
  523.  
  524.     def get_ext_fullname (self, ext_name):
  525.         if self.package is None:
  526.             return ext_name
  527.         else:
  528.             return self.package + '.' + ext_name
  529.  
  530.     def get_ext_filename (self, ext_name):
  531.         """Convert the name of an extension (eg. "foo.bar") into the name
  532.         of the file from which it will be loaded (eg. "foo/bar.so", or
  533.         "foo\bar.pyd").
  534.         """
  535.  
  536.         from distutils.sysconfig import get_config_var
  537.         ext_path = string.split(ext_name, '.')
  538.         # extensions in debug_mode are named 'module_d.pyd' under windows
  539.         so_ext = get_config_var('SO')
  540.         if os.name == 'nt' and self.debug:
  541.             return apply(os.path.join, ext_path) + '_d' + so_ext
  542.         return apply(os.path.join, ext_path) + so_ext
  543.  
  544.     def get_export_symbols (self, ext):
  545.         """Return the list of symbols that a shared extension has to
  546.         export.  This either uses 'ext.export_symbols' or, if it's not
  547.         provided, "init" + module_name.  Only relevant on Windows, where
  548.         the .pyd file (DLL) must export the module "init" function.
  549.         """
  550.  
  551.         initfunc_name = "init" + string.split(ext.name,'.')[-1]
  552.         if initfunc_name not in ext.export_symbols:
  553.             ext.export_symbols.append(initfunc_name)
  554.         return ext.export_symbols
  555.  
  556.     def get_libraries (self, ext):
  557.         """Return the list of libraries to link against when building a
  558.         shared extension.  On most platforms, this is just 'ext.libraries';
  559.         on Windows, we add the Python library (eg. python20.dll).
  560.         """
  561.         # The python library is always needed on Windows.  For MSVC, this
  562.         # is redundant, since the library is mentioned in a pragma in
  563.         # config.h that MSVC groks.  The other Windows compilers all seem
  564.         # to need it mentioned explicitly, though, so that's what we do.
  565.         # Append '_d' to the python import library on debug builds.
  566.         from distutils.msvccompiler import MSVCCompiler
  567.         if sys.platform == "win32" and \
  568.            not isinstance(self.compiler, MSVCCompiler):
  569.             template = "python%d%d"
  570.             if self.debug:
  571.                 template = template + '_d'
  572.             pythonlib = (template %
  573.                    (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
  574.             # don't extend ext.libraries, it may be shared with other
  575.             # extensions, it is a reference to the original list
  576.             return ext.libraries + [pythonlib]
  577.         else:
  578.             return ext.libraries
  579.  
  580. # class build_ext
  581.