Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes | Static Public Attributes
setup.PyBuildExt Class Reference
Inheritance diagram for setup.PyBuildExt:
Inheritance graph
[legend]
Collaboration diagram for setup.PyBuildExt:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def __init__
def build_extensions
def build_extension
def get_platform
def add_multiarch_paths
def detect_modules
def detect_tkinter_darwin
def detect_tkinter
def initialize_options
def finalize_options
def run
def check_extensions_list
def get_source_files
def get_outputs
def swig_sources
def find_swig
def get_ext_fullpath
def get_ext_fullname
def get_ext_filename
def get_export_symbols
def get_libraries

Public Attributes

 failed
 extensions
 build_lib
 plat_name
 build_temp
 inplace
 package
 include_dirs
 define
 undef
 libraries
 library_dirs
 rpath
 link_objects
 debug
 force
 compiler
 swig
 swig_cpp
 swig_opts
 user

Static Public Attributes

string description = "build C/C++ extensions (compile/link to build directory)"
string sep_by = " (separated by '%s')"
list user_options
list boolean_options = ['inplace', 'debug', 'force', 'swig-cpp']
list help_options

Detailed Description

Definition at line 155 of file setup.py.


Constructor & Destructor Documentation

def setup.PyBuildExt.__init__ (   self,
  dist 
)

Definition at line 157 of file setup.py.

00157 
00158     def __init__(self, dist):
00159         build_ext.__init__(self, dist)
00160         self.failed = []

Here is the caller graph for this function:


Member Function Documentation

Definition at line 373 of file setup.py.

00373 
00374     def add_multiarch_paths(self):
00375         # Debian/Ubuntu multiarch support.
00376         # https://wiki.ubuntu.com/MultiarchSpec
00377         if not find_executable('dpkg-architecture'):
00378             return
00379         tmpfile = os.path.join(self.build_temp, 'multiarch')
00380         if not os.path.exists(self.build_temp):
00381             os.makedirs(self.build_temp)
00382         ret = os.system(
00383             'dpkg-architecture -qDEB_HOST_MULTIARCH > %s 2> /dev/null' %
00384             tmpfile)
00385         try:
00386             if ret >> 8 == 0:
00387                 with open(tmpfile) as fp:
00388                     multiarch_path_component = fp.readline().strip()
00389                 add_dir_to_list(self.compiler.library_dirs,
00390                                 '/usr/lib/' + multiarch_path_component)
00391                 add_dir_to_list(self.compiler.include_dirs,
00392                                 '/usr/include/' + multiarch_path_component)
00393         finally:
00394             os.unlink(tmpfile)

Here is the call graph for this function:

Here is the caller graph for this function:

def setup.PyBuildExt.build_extension (   self,
  ext 
)

Reimplemented from distutils.command.build_ext.build_ext.

Definition at line 287 of file setup.py.

00287 
00288     def build_extension(self, ext):
00289 
00290         if ext.name == '_ctypes':
00291             if not self.configure_ctypes(ext):
00292                 return
00293 
00294         try:
00295             build_ext.build_extension(self, ext)
00296         except (CCompilerError, DistutilsError) as why:
00297             self.announce('WARNING: building of extension "%s" failed: %s' %
00298                           (ext.name, sys.exc_info()[1]))
00299             self.failed.append(ext.name)
00300             return
00301         # Workaround for Mac OS X: The Carbon-based modules cannot be
00302         # reliably imported into a command-line Python
00303         if 'Carbon' in ext.extra_link_args:
00304             self.announce(
00305                 'WARNING: skipping import check for Carbon-based "%s"' %
00306                 ext.name)
00307             return
00308 
00309         if self.get_platform() == 'darwin' and (
00310                 sys.maxsize > 2**32 and '-arch' in ext.extra_link_args):
00311             # Don't bother doing an import check when an extension was
00312             # build with an explicit '-arch' flag on OSX. That's currently
00313             # only used to build 32-bit only extensions in a 4-way
00314             # universal build and loading 32-bit code into a 64-bit
00315             # process will fail.
00316             self.announce(
00317                 'WARNING: skipping import check for "%s"' %
00318                 ext.name)
00319             return
00320 
00321         # Workaround for Cygwin: Cygwin currently has fork issues when many
00322         # modules have been imported
00323         if self.get_platform() == 'cygwin':
00324             self.announce('WARNING: skipping import check for Cygwin-based "%s"'
00325                 % ext.name)
00326             return
00327         ext_filename = os.path.join(
00328             self.build_lib,
00329             self.get_ext_filename(self.get_ext_fullname(ext.name)))
00330 
00331         # If the build directory didn't exist when setup.py was
00332         # started, sys.path_importer_cache has a negative result
00333         # cached.  Clear that cache before trying to import.
00334         sys.path_importer_cache.clear()
00335 
00336         try:
00337             imp.load_dynamic(ext.name, ext_filename)
00338         except ImportError as why:
00339             self.failed.append(ext.name)
00340             self.announce('*** WARNING: renaming "%s" since importing it'
00341                           ' failed: %s' % (ext.name, why), level=3)
00342             assert not self.inplace
00343             basename, tail = os.path.splitext(ext_filename)
00344             newname = basename + "_failed" + tail
00345             if os.path.exists(newname):
00346                 os.remove(newname)
00347             os.rename(ext_filename, newname)
00348 
00349             # XXX -- This relies on a Vile HACK in
00350             # distutils.command.build_ext.build_extension().  The
00351             # _built_objects attribute is stored there strictly for
00352             # use here.
00353             # If there is a failure, _built_objects may not be there,
00354             # so catch the AttributeError and move on.
00355             try:
00356                 for filename in self._built_objects:
00357                     os.remove(filename)
00358             except AttributeError:
00359                 self.announce('unable to remove files (ignored)')
00360         except:
00361             exc_type, why, tb = sys.exc_info()
00362             self.announce('*** WARNING: importing extension "%s" '
00363                           'failed with %s: %s' % (ext.name, exc_type, why),
00364                           level=3)
00365             self.failed.append(ext.name)

Here is the call graph for this function:

Reimplemented from distutils.command.build_ext.build_ext.

Definition at line 161 of file setup.py.

00161 
00162     def build_extensions(self):
00163 
00164         # Detect which modules should be compiled
00165         old_so = self.compiler.shared_lib_extension
00166         # Workaround PEP 3149 stuff
00167         self.compiler.shared_lib_extension = os.environ.get("SO", ".so")
00168         try:
00169             missing = self.detect_modules()
00170         finally:
00171             self.compiler.shared_lib_extension = old_so
00172 
00173         # Remove modules that are present on the disabled list
00174         extensions = [ext for ext in self.extensions
00175                       if ext.name not in disabled_module_list]
00176         # move ctypes to the end, it depends on other modules
00177         ext_map = dict((ext.name, i) for i, ext in enumerate(extensions))
00178         if "_ctypes" in ext_map:
00179             ctypes = extensions.pop(ext_map["_ctypes"])
00180             extensions.append(ctypes)
00181         self.extensions = extensions
00182 
00183         # Fix up the autodetected modules, prefixing all the source files
00184         # with Modules/.
00185         srcdir = sysconfig.get_config_var('srcdir')
00186         if not srcdir:
00187             # Maybe running on Windows but not using CYGWIN?
00188             raise ValueError("No source directory; cannot proceed.")
00189         srcdir = os.path.abspath(srcdir)
00190         moddirlist = [os.path.join(srcdir, 'Modules')]
00191 
00192         # Platform-dependent module source and include directories
00193         platform = self.get_platform()
00194 
00195         # Fix up the paths for scripts, too
00196         self.distribution.scripts = [os.path.join(srcdir, filename)
00197                                      for filename in self.distribution.scripts]
00198 
00199         # Python header files
00200         headers = [sysconfig.get_config_h_filename()]
00201         headers += glob(os.path.join(sysconfig.get_path('platinclude'), "*.h"))
00202 
00203         for ext in self.extensions[:]:
00204             ext.sources = [ find_module_file(filename, moddirlist)
00205                             for filename in ext.sources ]
00206             if ext.depends is not None:
00207                 ext.depends = [find_module_file(filename, moddirlist)
00208                                for filename in ext.depends]
00209             else:
00210                 ext.depends = []
00211             # re-compile extensions if a header file has been changed
00212             ext.depends.extend(headers)
00213 
00214             # If a module has already been built statically,
00215             # don't build it here
00216             if ext.name in sys.builtin_module_names:
00217                 self.extensions.remove(ext)
00218 
00219         # Parse Modules/Setup and Modules/Setup.local to figure out which
00220         # modules are turned on in the file.
00221         remove_modules = []
00222         for filename in ('Modules/Setup', 'Modules/Setup.local'):
00223             input = text_file.TextFile(filename, join_lines=1)
00224             while 1:
00225                 line = input.readline()
00226                 if not line: break
00227                 line = line.split()
00228                 remove_modules.append(line[0])
00229             input.close()
00230 
00231         for ext in self.extensions[:]:
00232             if ext.name in remove_modules:
00233                 self.extensions.remove(ext)
00234 
00235         # When you run "make CC=altcc" or something similar, you really want
00236         # those environment variables passed into the setup.py phase.  Here's
00237         # a small set of useful ones.
00238         compiler = os.environ.get('CC')
00239         args = {}
00240         # unfortunately, distutils doesn't let us provide separate C and C++
00241         # compilers
00242         if compiler is not None:
00243             (ccshared,cflags) = sysconfig.get_config_vars('CCSHARED','CFLAGS')
00244             args['compiler_so'] = compiler + ' ' + ccshared + ' ' + cflags
00245         self.compiler.set_executables(**args)
00246 
00247         # Not only do we write the builddir cookie, but we manually install
00248         # the shared modules directory if it isn't already in sys.path.
00249         # Otherwise trying to import the extensions after building them
00250         # will fail.
00251         with open(_BUILDDIR_COOKIE, "wb") as f:
00252             f.write(self.build_lib.encode('utf-8', 'surrogateescape'))
00253         abs_build_lib = os.path.join(os.getcwd(), self.build_lib)
00254         if abs_build_lib not in sys.path:
00255             sys.path.append(abs_build_lib)
00256 
00257         build_ext.build_extensions(self)
00258 
00259         longest = max([len(e.name) for e in self.extensions])
00260         if self.failed:
00261             longest = max(longest, max([len(name) for name in self.failed]))
00262 
00263         def print_three_column(lst):
00264             lst.sort(key=str.lower)
00265             # guarantee zip() doesn't drop anything
00266             while len(lst) % 3:
00267                 lst.append("")
00268             for e, f, g in zip(lst[::3], lst[1::3], lst[2::3]):
00269                 print("%-*s   %-*s   %-*s" % (longest, e, longest, f,
00270                                               longest, g))
00271 
00272         if missing:
00273             print()
00274             print("Python build finished, but the necessary bits to build "
00275                    "these modules were not found:")
00276             print_three_column(missing)
00277             print("To find the necessary bits, look in setup.py in"
00278                   " detect_modules() for the module's name.")
00279             print()
00280 
00281         if self.failed:
00282             failed = self.failed[:]
00283             print()
00284             print("Failed to build these modules:")
00285             print_three_column(failed)
00286             print()

Here is the call graph for this function:

def distutils.command.build_ext.build_ext.check_extensions_list (   self,
  extensions 
) [inherited]
Ensure that the list of extensions (presumably provided as a
command option 'extensions') is valid, i.e. it is a list of
Extension objects.  We also support the old-style list of 2-tuples,
where the tuples are (ext_name, build_info), which are converted to
Extension instances here.

Raise DistutilsSetupError if the structure is invalid anywhere;
just returns otherwise.

Definition at line 347 of file build_ext.py.

00347 
00348     def check_extensions_list(self, extensions):
00349         """Ensure that the list of extensions (presumably provided as a
00350         command option 'extensions') is valid, i.e. it is a list of
00351         Extension objects.  We also support the old-style list of 2-tuples,
00352         where the tuples are (ext_name, build_info), which are converted to
00353         Extension instances here.
00354 
00355         Raise DistutilsSetupError if the structure is invalid anywhere;
00356         just returns otherwise.
00357         """
00358         if not isinstance(extensions, list):
00359             raise DistutilsSetupError(
00360                   "'ext_modules' option must be a list of Extension instances")
00361 
00362         for i, ext in enumerate(extensions):
00363             if isinstance(ext, Extension):
00364                 continue                # OK! (assume type-checking done
00365                                         # by Extension constructor)
00366 
00367             if not isinstance(ext, tuple) or len(ext) != 2:
00368                 raise DistutilsSetupError(
00369                        "each element of 'ext_modules' option must be an "
00370                        "Extension instance or 2-tuple")
00371 
00372             ext_name, build_info = ext
00373 
00374             log.warn(("old-style (ext_name, build_info) tuple found in "
00375                       "ext_modules for extension '%s'"
00376                       "-- please convert to Extension instance" % ext_name))
00377 
00378             if not (isinstance(ext_name, str) and
00379                     extension_name_re.match(ext_name)):
00380                 raise DistutilsSetupError(
00381                        "first element of each tuple in 'ext_modules' "
00382                        "must be the extension name (a string)")
00383 
00384             if not isinstance(build_info, dict):
00385                 raise DistutilsSetupError(
00386                        "second element of each tuple in 'ext_modules' "
00387                        "must be a dictionary (build info)")
00388 
00389             # OK, the (ext_name, build_info) dict is type-safe: convert it
00390             # to an Extension instance.
00391             ext = Extension(ext_name, build_info['sources'])
00392 
00393             # Easy stuff: one-to-one mapping from dict elements to
00394             # instance attributes.
00395             for key in ('include_dirs', 'library_dirs', 'libraries',
00396                         'extra_objects', 'extra_compile_args',
00397                         'extra_link_args'):
00398                 val = build_info.get(key)
00399                 if val is not None:
00400                     setattr(ext, key, val)
00401 
00402             # Medium-easy stuff: same syntax/semantics, different names.
00403             ext.runtime_library_dirs = build_info.get('rpath')
00404             if 'def_file' in build_info:
00405                 log.warn("'def_file' element of build info dict "
00406                          "no longer supported")
00407 
00408             # Non-trivial stuff: 'macros' split into 'define_macros'
00409             # and 'undef_macros'.
00410             macros = build_info.get('macros')
00411             if macros:
00412                 ext.define_macros = []
00413                 ext.undef_macros = []
00414                 for macro in macros:
00415                     if not (isinstance(macro, tuple) and len(macro) in (1, 2)):
00416                         raise DistutilsSetupError(
00417                               "'macros' element of build info dict "
00418                               "must be 1- or 2-tuple")
00419                     if len(macro) == 1:
00420                         ext.undef_macros.append(macro[0])
00421                     elif len(macro) == 2:
00422                         ext.define_macros.append(macro)
00423 
00424             extensions[i] = ext

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 395 of file setup.py.

00395 
00396     def detect_modules(self):
00397         # Ensure that /usr/local is always used, but the local build
00398         # directories (i.e. '.' and 'Include') must be first.  See issue
00399         # 10520.
00400         add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib')
00401         add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
00402         self.add_multiarch_paths()
00403 
00404         # Add paths specified in the environment variables LDFLAGS and
00405         # CPPFLAGS for header and library files.
00406         # We must get the values from the Makefile and not the environment
00407         # directly since an inconsistently reproducible issue comes up where
00408         # the environment variable is not set even though the value were passed
00409         # into configure and stored in the Makefile (issue found on OS X 10.3).
00410         for env_var, arg_name, dir_list in (
00411                 ('LDFLAGS', '-R', self.compiler.runtime_library_dirs),
00412                 ('LDFLAGS', '-L', self.compiler.library_dirs),
00413                 ('CPPFLAGS', '-I', self.compiler.include_dirs)):
00414             env_val = sysconfig.get_config_var(env_var)
00415             if env_val:
00416                 # To prevent optparse from raising an exception about any
00417                 # options in env_val that it doesn't know about we strip out
00418                 # all double dashes and any dashes followed by a character
00419                 # that is not for the option we are dealing with.
00420                 #
00421                 # Please note that order of the regex is important!  We must
00422                 # strip out double-dashes first so that we don't end up with
00423                 # substituting "--Long" to "-Long" and thus lead to "ong" being
00424                 # used for a library directory.
00425                 env_val = re.sub(r'(^|\s+)-(-|(?!%s))' % arg_name[1],
00426                                  ' ', env_val)
00427                 parser = optparse.OptionParser()
00428                 # Make sure that allowing args interspersed with options is
00429                 # allowed
00430                 parser.allow_interspersed_args = True
00431                 parser.error = lambda msg: None
00432                 parser.add_option(arg_name, dest="dirs", action="append")
00433                 options = parser.parse_args(env_val.split())[0]
00434                 if options.dirs:
00435                     for directory in reversed(options.dirs):
00436                         add_dir_to_list(dir_list, directory)
00437 
00438         if os.path.normpath(sys.prefix) != '/usr' \
00439                 and not sysconfig.get_config_var('PYTHONFRAMEWORK'):
00440             # OSX note: Don't add LIBDIR and INCLUDEDIR to building a framework
00441             # (PYTHONFRAMEWORK is set) to avoid # linking problems when
00442             # building a framework with different architectures than
00443             # the one that is currently installed (issue #7473)
00444             add_dir_to_list(self.compiler.library_dirs,
00445                             sysconfig.get_config_var("LIBDIR"))
00446             add_dir_to_list(self.compiler.include_dirs,
00447                             sysconfig.get_config_var("INCLUDEDIR"))
00448 
00449         # lib_dirs and inc_dirs are used to search for files;
00450         # if a file is found in one of those directories, it can
00451         # be assumed that no additional -I,-L directives are needed.
00452         lib_dirs = self.compiler.library_dirs + [
00453             '/lib64', '/usr/lib64',
00454             '/lib', '/usr/lib',
00455             ]
00456         inc_dirs = self.compiler.include_dirs + ['/usr/include']
00457         exts = []
00458         missing = []
00459 
00460         config_h = sysconfig.get_config_h_filename()
00461         with open(config_h) as file:
00462             config_h_vars = sysconfig.parse_config_h(file)
00463 
00464         platform = self.get_platform()
00465         srcdir = sysconfig.get_config_var('srcdir')
00466 
00467         # OSF/1 and Unixware have some stuff in /usr/ccs/lib (like -ldb)
00468         if platform in ['osf1', 'unixware7', 'openunix8']:
00469             lib_dirs += ['/usr/ccs/lib']
00470 
00471         if platform == 'darwin':
00472             # This should work on any unixy platform ;-)
00473             # If the user has bothered specifying additional -I and -L flags
00474             # in OPT and LDFLAGS we might as well use them here.
00475             #
00476             # NOTE: using shlex.split would technically be more correct, but
00477             # also gives a bootstrap problem. Let's hope nobody uses
00478             # directories with whitespace in the name to store libraries.
00479             cflags, ldflags = sysconfig.get_config_vars(
00480                     'CFLAGS', 'LDFLAGS')
00481             for item in cflags.split():
00482                 if item.startswith('-I'):
00483                     inc_dirs.append(item[2:])
00484 
00485             for item in ldflags.split():
00486                 if item.startswith('-L'):
00487                     lib_dirs.append(item[2:])
00488 
00489         # Check for MacOS X, which doesn't need libm.a at all
00490         math_libs = ['m']
00491         if platform == 'darwin':
00492             math_libs = []
00493 
00494         # XXX Omitted modules: gl, pure, dl, SGI-specific modules
00495 
00496         #
00497         # The following modules are all pretty straightforward, and compile
00498         # on pretty much any POSIXish platform.
00499         #
00500 
00501         # array objects
00502         exts.append( Extension('array', ['arraymodule.c']) )
00503         # complex math library functions
00504         exts.append( Extension('cmath', ['cmathmodule.c', '_math.c'],
00505                                depends=['_math.h'],
00506                                libraries=math_libs) )
00507         # math library functions, e.g. sin()
00508         exts.append( Extension('math',  ['mathmodule.c', '_math.c'],
00509                                depends=['_math.h'],
00510                                libraries=math_libs) )
00511         # time operations and variables
00512         exts.append( Extension('time', ['timemodule.c', '_time.c'],
00513                                libraries=math_libs) )
00514         exts.append( Extension('_datetime', ['_datetimemodule.c', '_time.c'],
00515                                libraries=math_libs) )
00516         # random number generator implemented in C
00517         exts.append( Extension("_random", ["_randommodule.c"]) )
00518         # bisect
00519         exts.append( Extension("_bisect", ["_bisectmodule.c"]) )
00520         # heapq
00521         exts.append( Extension("_heapq", ["_heapqmodule.c"]) )
00522         # C-optimized pickle replacement
00523         exts.append( Extension("_pickle", ["_pickle.c"]) )
00524         # atexit
00525         exts.append( Extension("atexit", ["atexitmodule.c"]) )
00526         # _json speedups
00527         exts.append( Extension("_json", ["_json.c"]) )
00528         # Python C API test module
00529         exts.append( Extension('_testcapi', ['_testcapimodule.c'],
00530                                depends=['testcapi_long.h']) )
00531         # profiler (_lsprof is for cProfile.py)
00532         exts.append( Extension('_lsprof', ['_lsprof.c', 'rotatingtree.c']) )
00533         # static Unicode character database
00534         exts.append( Extension('unicodedata', ['unicodedata.c']) )
00535 
00536         # Modules with some UNIX dependencies -- on by default:
00537         # (If you have a really backward UNIX, select and socket may not be
00538         # supported...)
00539 
00540         # fcntl(2) and ioctl(2)
00541         libs = []
00542         if (config_h_vars.get('FLOCK_NEEDS_LIBBSD', False)):
00543             # May be necessary on AIX for flock function
00544             libs = ['bsd']
00545         exts.append( Extension('fcntl', ['fcntlmodule.c'], libraries=libs) )
00546         # pwd(3)
00547         exts.append( Extension('pwd', ['pwdmodule.c']) )
00548         # grp(3)
00549         exts.append( Extension('grp', ['grpmodule.c']) )
00550         # spwd, shadow passwords
00551         if (config_h_vars.get('HAVE_GETSPNAM', False) or
00552                 config_h_vars.get('HAVE_GETSPENT', False)):
00553             exts.append( Extension('spwd', ['spwdmodule.c']) )
00554         else:
00555             missing.append('spwd')
00556 
00557         # select(2); not on ancient System V
00558         exts.append( Extension('select', ['selectmodule.c']) )
00559 
00560         # Fred Drake's interface to the Python parser
00561         exts.append( Extension('parser', ['parsermodule.c']) )
00562 
00563         # Memory-mapped files (also works on Win32).
00564         exts.append( Extension('mmap', ['mmapmodule.c']) )
00565 
00566         # Lance Ellinghaus's syslog module
00567         # syslog daemon interface
00568         exts.append( Extension('syslog', ['syslogmodule.c']) )
00569 
00570         #
00571         # Here ends the simple stuff.  From here on, modules need certain
00572         # libraries, are platform-specific, or present other surprises.
00573         #
00574 
00575         # Multimedia modules
00576         # These don't work for 64-bit platforms!!!
00577         # These represent audio samples or images as strings:
00578 
00579         # Operations on audio samples
00580         # According to #993173, this one should actually work fine on
00581         # 64-bit platforms.
00582         exts.append( Extension('audioop', ['audioop.c']) )
00583 
00584         # readline
00585         do_readline = self.compiler.find_library_file(lib_dirs, 'readline')
00586         readline_termcap_library = ""
00587         curses_library = ""
00588         # Determine if readline is already linked against curses or tinfo.
00589         if do_readline and find_executable('ldd'):
00590             # Cannot use os.popen here in py3k.
00591             tmpfile = os.path.join(self.build_temp, 'readline_termcap_lib')
00592             if not os.path.exists(self.build_temp):
00593                 os.makedirs(self.build_temp)
00594             ret = os.system("ldd %s > %s" % (do_readline, tmpfile))
00595             if ret >> 8 == 0:
00596                 with open(tmpfile) as fp:
00597                     for ln in fp:
00598                         if 'curses' in ln:
00599                             readline_termcap_library = re.sub(
00600                                 r'.*lib(n?cursesw?)\.so.*', r'\1', ln
00601                             ).rstrip()
00602                             break
00603                         # termcap interface split out from ncurses
00604                         if 'tinfo' in ln:
00605                             readline_termcap_library = 'tinfo'
00606                             break
00607             os.unlink(tmpfile)
00608         # Issue 7384: If readline is already linked against curses,
00609         # use the same library for the readline and curses modules.
00610         if 'curses' in readline_termcap_library:
00611             curses_library = readline_termcap_library
00612         elif self.compiler.find_library_file(lib_dirs, 'ncursesw'):
00613             curses_library = 'ncursesw'
00614         elif self.compiler.find_library_file(lib_dirs, 'ncurses'):
00615             curses_library = 'ncurses'
00616         elif self.compiler.find_library_file(lib_dirs, 'curses'):
00617             curses_library = 'curses'
00618 
00619         if platform == 'darwin':
00620             os_release = int(os.uname()[2].split('.')[0])
00621             dep_target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
00622             if dep_target and dep_target.split('.') < ['10', '5']:
00623                 os_release = 8
00624             if os_release < 9:
00625                 # MacOSX 10.4 has a broken readline. Don't try to build
00626                 # the readline module unless the user has installed a fixed
00627                 # readline package
00628                 if find_file('readline/rlconf.h', inc_dirs, []) is None:
00629                     do_readline = False
00630         if do_readline:
00631             if platform == 'darwin' and os_release < 9:
00632                 # In every directory on the search path search for a dynamic
00633                 # library and then a static library, instead of first looking
00634                 # for dynamic libraries on the entire path.
00635                 # This way a staticly linked custom readline gets picked up
00636                 # before the (possibly broken) dynamic library in /usr/lib.
00637                 readline_extra_link_args = ('-Wl,-search_paths_first',)
00638             else:
00639                 readline_extra_link_args = ()
00640 
00641             readline_libs = ['readline']
00642             if readline_termcap_library:
00643                 pass # Issue 7384: Already linked against curses or tinfo.
00644             elif curses_library:
00645                 readline_libs.append(curses_library)
00646             elif self.compiler.find_library_file(lib_dirs +
00647                                                      ['/usr/lib/termcap'],
00648                                                      'termcap'):
00649                 readline_libs.append('termcap')
00650             exts.append( Extension('readline', ['readline.c'],
00651                                    library_dirs=['/usr/lib/termcap'],
00652                                    extra_link_args=readline_extra_link_args,
00653                                    libraries=readline_libs) )
00654         else:
00655             missing.append('readline')
00656 
00657         # crypt module.
00658 
00659         if self.compiler.find_library_file(lib_dirs, 'crypt'):
00660             libs = ['crypt']
00661         else:
00662             libs = []
00663         exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) )
00664 
00665         # CSV files
00666         exts.append( Extension('_csv', ['_csv.c']) )
00667 
00668         # POSIX subprocess module helper.
00669         exts.append( Extension('_posixsubprocess', ['_posixsubprocess.c']) )
00670 
00671         # socket(2)
00672         exts.append( Extension('_socket', ['socketmodule.c'],
00673                                depends = ['socketmodule.h']) )
00674         # Detect SSL support for the socket module (via _ssl)
00675         search_for_ssl_incs_in = [
00676                               '/usr/local/ssl/include',
00677                               '/usr/contrib/ssl/include/'
00678                              ]
00679         ssl_incs = find_file('openssl/ssl.h', inc_dirs,
00680                              search_for_ssl_incs_in
00681                              )
00682         if ssl_incs is not None:
00683             krb5_h = find_file('krb5.h', inc_dirs,
00684                                ['/usr/kerberos/include'])
00685             if krb5_h:
00686                 ssl_incs += krb5_h
00687         ssl_libs = find_library_file(self.compiler, 'ssl',lib_dirs,
00688                                      ['/usr/local/ssl/lib',
00689                                       '/usr/contrib/ssl/lib/'
00690                                      ] )
00691 
00692         if (ssl_incs is not None and
00693             ssl_libs is not None):
00694             exts.append( Extension('_ssl', ['_ssl.c'],
00695                                    include_dirs = ssl_incs,
00696                                    library_dirs = ssl_libs,
00697                                    libraries = ['ssl', 'crypto'],
00698                                    depends = ['socketmodule.h']), )
00699         else:
00700             missing.append('_ssl')
00701 
00702         # find out which version of OpenSSL we have
00703         openssl_ver = 0
00704         openssl_ver_re = re.compile(
00705             '^\s*#\s*define\s+OPENSSL_VERSION_NUMBER\s+(0x[0-9a-fA-F]+)' )
00706 
00707         # look for the openssl version header on the compiler search path.
00708         opensslv_h = find_file('openssl/opensslv.h', [],
00709                 inc_dirs + search_for_ssl_incs_in)
00710         if opensslv_h:
00711             name = os.path.join(opensslv_h[0], 'openssl/opensslv.h')
00712             if sys.platform == 'darwin' and is_macosx_sdk_path(name):
00713                 name = os.path.join(macosx_sdk_root(), name[1:])
00714             try:
00715                 with open(name, 'r') as incfile:
00716                     for line in incfile:
00717                         m = openssl_ver_re.match(line)
00718                         if m:
00719                             openssl_ver = eval(m.group(1))
00720             except IOError as msg:
00721                 print("IOError while reading opensshv.h:", msg)
00722                 pass
00723 
00724         #print('openssl_ver = 0x%08x' % openssl_ver)
00725         min_openssl_ver = 0x00907000
00726         have_any_openssl = ssl_incs is not None and ssl_libs is not None
00727         have_usable_openssl = (have_any_openssl and
00728                                openssl_ver >= min_openssl_ver)
00729 
00730         if have_any_openssl:
00731             if have_usable_openssl:
00732                 # The _hashlib module wraps optimized implementations
00733                 # of hash functions from the OpenSSL library.
00734                 exts.append( Extension('_hashlib', ['_hashopenssl.c'],
00735                                        depends = ['hashlib.h'],
00736                                        include_dirs = ssl_incs,
00737                                        library_dirs = ssl_libs,
00738                                        libraries = ['ssl', 'crypto']) )
00739             else:
00740                 print("warning: openssl 0x%08x is too old for _hashlib" %
00741                       openssl_ver)
00742                 missing.append('_hashlib')
00743 
00744         min_sha2_openssl_ver = 0x00908000
00745         if COMPILED_WITH_PYDEBUG or openssl_ver < min_sha2_openssl_ver:
00746             # OpenSSL doesn't do these until 0.9.8 so we'll bring our own hash
00747             exts.append( Extension('_sha256', ['sha256module.c'],
00748                                    depends=['hashlib.h']) )
00749             exts.append( Extension('_sha512', ['sha512module.c'],
00750                                    depends=['hashlib.h']) )
00751 
00752         if COMPILED_WITH_PYDEBUG or not have_usable_openssl:
00753             # no openssl at all, use our own md5 and sha1
00754             exts.append( Extension('_md5', ['md5module.c'],
00755                                    depends=['hashlib.h']) )
00756             exts.append( Extension('_sha1', ['sha1module.c'],
00757                                    depends=['hashlib.h']) )
00758 
00759         # Modules that provide persistent dictionary-like semantics.  You will
00760         # probably want to arrange for at least one of them to be available on
00761         # your machine, though none are defined by default because of library
00762         # dependencies.  The Python module dbm/__init__.py provides an
00763         # implementation independent wrapper for these; dbm/dumb.py provides
00764         # similar functionality (but slower of course) implemented in Python.
00765 
00766         # Sleepycat^WOracle Berkeley DB interface.
00767         #  http://www.oracle.com/database/berkeley-db/db/index.html
00768         #
00769         # This requires the Sleepycat^WOracle DB code. The supported versions
00770         # are set below.  Visit the URL above to download
00771         # a release.  Most open source OSes come with one or more
00772         # versions of BerkeleyDB already installed.
00773 
00774         max_db_ver = (5, 1)
00775         min_db_ver = (3, 3)
00776         db_setup_debug = False   # verbose debug prints from this script?
00777 
00778         def allow_db_ver(db_ver):
00779             """Returns a boolean if the given BerkeleyDB version is acceptable.
00780 
00781             Args:
00782               db_ver: A tuple of the version to verify.
00783             """
00784             if not (min_db_ver <= db_ver <= max_db_ver):
00785                 return False
00786             return True
00787 
00788         def gen_db_minor_ver_nums(major):
00789             if major == 4:
00790                 for x in range(max_db_ver[1]+1):
00791                     if allow_db_ver((4, x)):
00792                         yield x
00793             elif major == 3:
00794                 for x in (3,):
00795                     if allow_db_ver((3, x)):
00796                         yield x
00797             else:
00798                 raise ValueError("unknown major BerkeleyDB version", major)
00799 
00800         # construct a list of paths to look for the header file in on
00801         # top of the normal inc_dirs.
00802         db_inc_paths = [
00803             '/usr/include/db4',
00804             '/usr/local/include/db4',
00805             '/opt/sfw/include/db4',
00806             '/usr/include/db3',
00807             '/usr/local/include/db3',
00808             '/opt/sfw/include/db3',
00809             # Fink defaults (http://fink.sourceforge.net/)
00810             '/sw/include/db4',
00811             '/sw/include/db3',
00812         ]
00813         # 4.x minor number specific paths
00814         for x in gen_db_minor_ver_nums(4):
00815             db_inc_paths.append('/usr/include/db4%d' % x)
00816             db_inc_paths.append('/usr/include/db4.%d' % x)
00817             db_inc_paths.append('/usr/local/BerkeleyDB.4.%d/include' % x)
00818             db_inc_paths.append('/usr/local/include/db4%d' % x)
00819             db_inc_paths.append('/pkg/db-4.%d/include' % x)
00820             db_inc_paths.append('/opt/db-4.%d/include' % x)
00821             # MacPorts default (http://www.macports.org/)
00822             db_inc_paths.append('/opt/local/include/db4%d' % x)
00823         # 3.x minor number specific paths
00824         for x in gen_db_minor_ver_nums(3):
00825             db_inc_paths.append('/usr/include/db3%d' % x)
00826             db_inc_paths.append('/usr/local/BerkeleyDB.3.%d/include' % x)
00827             db_inc_paths.append('/usr/local/include/db3%d' % x)
00828             db_inc_paths.append('/pkg/db-3.%d/include' % x)
00829             db_inc_paths.append('/opt/db-3.%d/include' % x)
00830 
00831         # Add some common subdirectories for Sleepycat DB to the list,
00832         # based on the standard include directories. This way DB3/4 gets
00833         # picked up when it is installed in a non-standard prefix and
00834         # the user has added that prefix into inc_dirs.
00835         std_variants = []
00836         for dn in inc_dirs:
00837             std_variants.append(os.path.join(dn, 'db3'))
00838             std_variants.append(os.path.join(dn, 'db4'))
00839             for x in gen_db_minor_ver_nums(4):
00840                 std_variants.append(os.path.join(dn, "db4%d"%x))
00841                 std_variants.append(os.path.join(dn, "db4.%d"%x))
00842             for x in gen_db_minor_ver_nums(3):
00843                 std_variants.append(os.path.join(dn, "db3%d"%x))
00844                 std_variants.append(os.path.join(dn, "db3.%d"%x))
00845 
00846         db_inc_paths = std_variants + db_inc_paths
00847         db_inc_paths = [p for p in db_inc_paths if os.path.exists(p)]
00848 
00849         db_ver_inc_map = {}
00850 
00851         if sys.platform == 'darwin':
00852             sysroot = macosx_sdk_root()
00853 
00854         class db_found(Exception): pass
00855         try:
00856             # See whether there is a Sleepycat header in the standard
00857             # search path.
00858             for d in inc_dirs + db_inc_paths:
00859                 f = os.path.join(d, "db.h")
00860                 if sys.platform == 'darwin' and is_macosx_sdk_path(d):
00861                     f = os.path.join(sysroot, d[1:], "db.h")
00862 
00863                 if db_setup_debug: print("db: looking for db.h in", f)
00864                 if os.path.exists(f):
00865                     with open(f, 'rb') as file:
00866                         f = file.read()
00867                     m = re.search(br"#define\WDB_VERSION_MAJOR\W(\d+)", f)
00868                     if m:
00869                         db_major = int(m.group(1))
00870                         m = re.search(br"#define\WDB_VERSION_MINOR\W(\d+)", f)
00871                         db_minor = int(m.group(1))
00872                         db_ver = (db_major, db_minor)
00873 
00874                         # Avoid 4.6 prior to 4.6.21 due to a BerkeleyDB bug
00875                         if db_ver == (4, 6):
00876                             m = re.search(br"#define\WDB_VERSION_PATCH\W(\d+)", f)
00877                             db_patch = int(m.group(1))
00878                             if db_patch < 21:
00879                                 print("db.h:", db_ver, "patch", db_patch,
00880                                       "being ignored (4.6.x must be >= 4.6.21)")
00881                                 continue
00882 
00883                         if ( (db_ver not in db_ver_inc_map) and
00884                             allow_db_ver(db_ver) ):
00885                             # save the include directory with the db.h version
00886                             # (first occurrence only)
00887                             db_ver_inc_map[db_ver] = d
00888                             if db_setup_debug:
00889                                 print("db.h: found", db_ver, "in", d)
00890                         else:
00891                             # we already found a header for this library version
00892                             if db_setup_debug: print("db.h: ignoring", d)
00893                     else:
00894                         # ignore this header, it didn't contain a version number
00895                         if db_setup_debug:
00896                             print("db.h: no version number version in", d)
00897 
00898             db_found_vers = list(db_ver_inc_map.keys())
00899             db_found_vers.sort()
00900 
00901             while db_found_vers:
00902                 db_ver = db_found_vers.pop()
00903                 db_incdir = db_ver_inc_map[db_ver]
00904 
00905                 # check lib directories parallel to the location of the header
00906                 db_dirs_to_check = [
00907                     db_incdir.replace("include", 'lib64'),
00908                     db_incdir.replace("include", 'lib'),
00909                 ]
00910 
00911                 if sys.platform != 'darwin':
00912                     db_dirs_to_check = list(filter(os.path.isdir, db_dirs_to_check))
00913 
00914                 else:
00915                     # Same as other branch, but takes OSX SDK into account
00916                     tmp = []
00917                     for dn in db_dirs_to_check:
00918                         if is_macosx_sdk_path(dn):
00919                             if os.path.isdir(os.path.join(sysroot, dn[1:])):
00920                                 tmp.append(dn)
00921                         else:
00922                             if os.path.isdir(dn):
00923                                 tmp.append(dn)
00924                     db_dirs_to_check = tmp
00925 
00926                     db_dirs_to_check = tmp
00927 
00928                 # Look for a version specific db-X.Y before an ambiguous dbX
00929                 # XXX should we -ever- look for a dbX name?  Do any
00930                 # systems really not name their library by version and
00931                 # symlink to more general names?
00932                 for dblib in (('db-%d.%d' % db_ver),
00933                               ('db%d%d' % db_ver),
00934                               ('db%d' % db_ver[0])):
00935                     dblib_file = self.compiler.find_library_file(
00936                                     db_dirs_to_check + lib_dirs, dblib )
00937                     if dblib_file:
00938                         dblib_dir = [ os.path.abspath(os.path.dirname(dblib_file)) ]
00939                         raise db_found
00940                     else:
00941                         if db_setup_debug: print("db lib: ", dblib, "not found")
00942 
00943         except db_found:
00944             if db_setup_debug:
00945                 print("bsddb using BerkeleyDB lib:", db_ver, dblib)
00946                 print("bsddb lib dir:", dblib_dir, " inc dir:", db_incdir)
00947             db_incs = [db_incdir]
00948             dblibs = [dblib]
00949         else:
00950             if db_setup_debug: print("db: no appropriate library found")
00951             db_incs = None
00952             dblibs = []
00953             dblib_dir = None
00954 
00955         # The sqlite interface
00956         sqlite_setup_debug = False   # verbose debug prints from this script?
00957 
00958         # We hunt for #define SQLITE_VERSION "n.n.n"
00959         # We need to find >= sqlite version 3.0.8
00960         sqlite_incdir = sqlite_libdir = None
00961         sqlite_inc_paths = [ '/usr/include',
00962                              '/usr/include/sqlite',
00963                              '/usr/include/sqlite3',
00964                              '/usr/local/include',
00965                              '/usr/local/include/sqlite',
00966                              '/usr/local/include/sqlite3',
00967                            ]
00968         MIN_SQLITE_VERSION_NUMBER = (3, 0, 8)
00969         MIN_SQLITE_VERSION = ".".join([str(x)
00970                                     for x in MIN_SQLITE_VERSION_NUMBER])
00971 
00972         # Scan the default include directories before the SQLite specific
00973         # ones. This allows one to override the copy of sqlite on OSX,
00974         # where /usr/include contains an old version of sqlite.
00975         if sys.platform == 'darwin':
00976             sysroot = macosx_sdk_root()
00977 
00978         for d in inc_dirs + sqlite_inc_paths:
00979             f = os.path.join(d, "sqlite3.h")
00980 
00981             if sys.platform == 'darwin' and is_macosx_sdk_path(d):
00982                 f = os.path.join(sysroot, d[1:], "sqlite3.h")
00983 
00984             if os.path.exists(f):
00985                 if sqlite_setup_debug: print("sqlite: found %s"%f)
00986                 with open(f) as file:
00987                     incf = file.read()
00988                 m = re.search(
00989                     r'\s*.*#\s*.*define\s.*SQLITE_VERSION\W*"(.*)"', incf)
00990                 if m:
00991                     sqlite_version = m.group(1)
00992                     sqlite_version_tuple = tuple([int(x)
00993                                         for x in sqlite_version.split(".")])
00994                     if sqlite_version_tuple >= MIN_SQLITE_VERSION_NUMBER:
00995                         # we win!
00996                         if sqlite_setup_debug:
00997                             print("%s/sqlite3.h: version %s"%(d, sqlite_version))
00998                         sqlite_incdir = d
00999                         break
01000                     else:
01001                         if sqlite_setup_debug:
01002                             print("%s: version %d is too old, need >= %s"%(d,
01003                                         sqlite_version, MIN_SQLITE_VERSION))
01004                 elif sqlite_setup_debug:
01005                     print("sqlite: %s had no SQLITE_VERSION"%(f,))
01006 
01007         if sqlite_incdir:
01008             sqlite_dirs_to_check = [
01009                 os.path.join(sqlite_incdir, '..', 'lib64'),
01010                 os.path.join(sqlite_incdir, '..', 'lib'),
01011                 os.path.join(sqlite_incdir, '..', '..', 'lib64'),
01012                 os.path.join(sqlite_incdir, '..', '..', 'lib'),
01013             ]
01014             sqlite_libfile = self.compiler.find_library_file(
01015                                 sqlite_dirs_to_check + lib_dirs, 'sqlite3')
01016             if sqlite_libfile:
01017                 sqlite_libdir = [os.path.abspath(os.path.dirname(sqlite_libfile))]
01018 
01019         if sqlite_incdir and sqlite_libdir:
01020             sqlite_srcs = ['_sqlite/cache.c',
01021                 '_sqlite/connection.c',
01022                 '_sqlite/cursor.c',
01023                 '_sqlite/microprotocols.c',
01024                 '_sqlite/module.c',
01025                 '_sqlite/prepare_protocol.c',
01026                 '_sqlite/row.c',
01027                 '_sqlite/statement.c',
01028                 '_sqlite/util.c', ]
01029 
01030             sqlite_defines = []
01031             if sys.platform != "win32":
01032                 sqlite_defines.append(('MODULE_NAME', '"sqlite3"'))
01033             else:
01034                 sqlite_defines.append(('MODULE_NAME', '\\"sqlite3\\"'))
01035 
01036             # Enable support for loadable extensions in the sqlite3 module
01037             # if --enable-loadable-sqlite-extensions configure option is used.
01038             if '--enable-loadable-sqlite-extensions' not in sysconfig.get_config_var("CONFIG_ARGS"):
01039                 sqlite_defines.append(("SQLITE_OMIT_LOAD_EXTENSION", "1"))
01040 
01041             if sys.platform == 'darwin':
01042                 # In every directory on the search path search for a dynamic
01043                 # library and then a static library, instead of first looking
01044                 # for dynamic libraries on the entire path.
01045                 # This way a statically linked custom sqlite gets picked up
01046                 # before the dynamic library in /usr/lib.
01047                 sqlite_extra_link_args = ('-Wl,-search_paths_first',)
01048             else:
01049                 sqlite_extra_link_args = ()
01050 
01051             exts.append(Extension('_sqlite3', sqlite_srcs,
01052                                   define_macros=sqlite_defines,
01053                                   include_dirs=["Modules/_sqlite",
01054                                                 sqlite_incdir],
01055                                   library_dirs=sqlite_libdir,
01056                                   runtime_library_dirs=sqlite_libdir,
01057                                   extra_link_args=sqlite_extra_link_args,
01058                                   libraries=["sqlite3",]))
01059         else:
01060             missing.append('_sqlite3')
01061 
01062         dbm_order = ['gdbm']
01063         # The standard Unix dbm module:
01064         if platform not in ['cygwin']:
01065             config_args = [arg.strip("'")
01066                            for arg in sysconfig.get_config_var("CONFIG_ARGS").split()]
01067             dbm_args = [arg for arg in config_args
01068                         if arg.startswith('--with-dbmliborder=')]
01069             if dbm_args:
01070                 dbm_order = [arg.split('=')[-1] for arg in dbm_args][-1].split(":")
01071             else:
01072                 dbm_order = "ndbm:gdbm:bdb".split(":")
01073             dbmext = None
01074             for cand in dbm_order:
01075                 if cand == "ndbm":
01076                     if find_file("ndbm.h", inc_dirs, []) is not None:
01077                         # Some systems have -lndbm, others don't
01078                         if self.compiler.find_library_file(lib_dirs,
01079                                                                'ndbm'):
01080                             ndbm_libs = ['ndbm']
01081                         else:
01082                             ndbm_libs = []
01083                         print("building dbm using ndbm")
01084                         dbmext = Extension('_dbm', ['_dbmmodule.c'],
01085                                            define_macros=[
01086                                                ('HAVE_NDBM_H',None),
01087                                                ],
01088                                            libraries=ndbm_libs)
01089                         break
01090 
01091                 elif cand == "gdbm":
01092                     if self.compiler.find_library_file(lib_dirs, 'gdbm'):
01093                         gdbm_libs = ['gdbm']
01094                         if self.compiler.find_library_file(lib_dirs,
01095                                                                'gdbm_compat'):
01096                             gdbm_libs.append('gdbm_compat')
01097                         if find_file("gdbm/ndbm.h", inc_dirs, []) is not None:
01098                             print("building dbm using gdbm")
01099                             dbmext = Extension(
01100                                 '_dbm', ['_dbmmodule.c'],
01101                                 define_macros=[
01102                                     ('HAVE_GDBM_NDBM_H', None),
01103                                     ],
01104                                 libraries = gdbm_libs)
01105                             break
01106                         if find_file("gdbm-ndbm.h", inc_dirs, []) is not None:
01107                             print("building dbm using gdbm")
01108                             dbmext = Extension(
01109                                 '_dbm', ['_dbmmodule.c'],
01110                                 define_macros=[
01111                                     ('HAVE_GDBM_DASH_NDBM_H', None),
01112                                     ],
01113                                 libraries = gdbm_libs)
01114                             break
01115                 elif cand == "bdb":
01116                     if db_incs is not None:
01117                         print("building dbm using bdb")
01118                         dbmext = Extension('_dbm', ['_dbmmodule.c'],
01119                                            library_dirs=dblib_dir,
01120                                            runtime_library_dirs=dblib_dir,
01121                                            include_dirs=db_incs,
01122                                            define_macros=[
01123                                                ('HAVE_BERKDB_H', None),
01124                                                ('DB_DBM_HSEARCH', None),
01125                                                ],
01126                                            libraries=dblibs)
01127                         break
01128             if dbmext is not None:
01129                 exts.append(dbmext)
01130             else:
01131                 missing.append('_dbm')
01132 
01133         # Anthony Baxter's gdbm module.  GNU dbm(3) will require -lgdbm:
01134         if ('gdbm' in dbm_order and
01135             self.compiler.find_library_file(lib_dirs, 'gdbm')):
01136             exts.append( Extension('_gdbm', ['_gdbmmodule.c'],
01137                                    libraries = ['gdbm'] ) )
01138         else:
01139             missing.append('_gdbm')
01140 
01141         # Unix-only modules
01142         if platform != 'win32':
01143             # Steen Lumholt's termios module
01144             exts.append( Extension('termios', ['termios.c']) )
01145             # Jeremy Hylton's rlimit interface
01146             exts.append( Extension('resource', ['resource.c']) )
01147 
01148             # Sun yellow pages. Some systems have the functions in libc.
01149             if (platform not in ['cygwin', 'qnx6'] and
01150                 find_file('rpcsvc/yp_prot.h', inc_dirs, []) is not None):
01151                 if (self.compiler.find_library_file(lib_dirs, 'nsl')):
01152                     libs = ['nsl']
01153                 else:
01154                     libs = []
01155                 exts.append( Extension('nis', ['nismodule.c'],
01156                                        libraries = libs) )
01157             else:
01158                 missing.append('nis')
01159         else:
01160             missing.extend(['nis', 'resource', 'termios'])
01161 
01162         # Curses support, requiring the System V version of curses, often
01163         # provided by the ncurses library.
01164         panel_library = 'panel'
01165         if curses_library.startswith('ncurses'):
01166             if curses_library == 'ncursesw':
01167                 # Bug 1464056: If _curses.so links with ncursesw,
01168                 # _curses_panel.so must link with panelw.
01169                 panel_library = 'panelw'
01170             curses_libs = [curses_library]
01171             exts.append( Extension('_curses', ['_cursesmodule.c'],
01172                                    libraries = curses_libs) )
01173         elif curses_library == 'curses' and platform != 'darwin':
01174                 # OSX has an old Berkeley curses, not good enough for
01175                 # the _curses module.
01176             if (self.compiler.find_library_file(lib_dirs, 'terminfo')):
01177                 curses_libs = ['curses', 'terminfo']
01178             elif (self.compiler.find_library_file(lib_dirs, 'termcap')):
01179                 curses_libs = ['curses', 'termcap']
01180             else:
01181                 curses_libs = ['curses']
01182 
01183             exts.append( Extension('_curses', ['_cursesmodule.c'],
01184                                    libraries = curses_libs) )
01185         else:
01186             missing.append('_curses')
01187 
01188         # If the curses module is enabled, check for the panel module
01189         if (module_enabled(exts, '_curses') and
01190             self.compiler.find_library_file(lib_dirs, panel_library)):
01191             exts.append( Extension('_curses_panel', ['_curses_panel.c'],
01192                                    libraries = [panel_library] + curses_libs) )
01193         else:
01194             missing.append('_curses_panel')
01195 
01196         # Andrew Kuchling's zlib module.  Note that some versions of zlib
01197         # 1.1.3 have security problems.  See CERT Advisory CA-2002-07:
01198         # http://www.cert.org/advisories/CA-2002-07.html
01199         #
01200         # zlib 1.1.4 is fixed, but at least one vendor (RedHat) has decided to
01201         # patch its zlib 1.1.3 package instead of upgrading to 1.1.4.  For
01202         # now, we still accept 1.1.3, because we think it's difficult to
01203         # exploit this in Python, and we'd rather make it RedHat's problem
01204         # than our problem <wink>.
01205         #
01206         # You can upgrade zlib to version 1.1.4 yourself by going to
01207         # http://www.gzip.org/zlib/
01208         zlib_inc = find_file('zlib.h', [], inc_dirs)
01209         have_zlib = False
01210         if zlib_inc is not None:
01211             zlib_h = zlib_inc[0] + '/zlib.h'
01212             version = '"0.0.0"'
01213             version_req = '"1.1.3"'
01214             with open(zlib_h) as fp:
01215                 while 1:
01216                     line = fp.readline()
01217                     if not line:
01218                         break
01219                     if line.startswith('#define ZLIB_VERSION'):
01220                         version = line.split()[2]
01221                         break
01222             if version >= version_req:
01223                 if (self.compiler.find_library_file(lib_dirs, 'z')):
01224                     if sys.platform == "darwin":
01225                         zlib_extra_link_args = ('-Wl,-search_paths_first',)
01226                     else:
01227                         zlib_extra_link_args = ()
01228                     exts.append( Extension('zlib', ['zlibmodule.c'],
01229                                            libraries = ['z'],
01230                                            extra_link_args = zlib_extra_link_args))
01231                     have_zlib = True
01232                 else:
01233                     missing.append('zlib')
01234             else:
01235                 missing.append('zlib')
01236         else:
01237             missing.append('zlib')
01238 
01239         # Helper module for various ascii-encoders.  Uses zlib for an optimized
01240         # crc32 if we have it.  Otherwise binascii uses its own.
01241         if have_zlib:
01242             extra_compile_args = ['-DUSE_ZLIB_CRC32']
01243             libraries = ['z']
01244             extra_link_args = zlib_extra_link_args
01245         else:
01246             extra_compile_args = []
01247             libraries = []
01248             extra_link_args = []
01249         exts.append( Extension('binascii', ['binascii.c'],
01250                                extra_compile_args = extra_compile_args,
01251                                libraries = libraries,
01252                                extra_link_args = extra_link_args) )
01253 
01254         # Gustavo Niemeyer's bz2 module.
01255         if (self.compiler.find_library_file(lib_dirs, 'bz2')):
01256             if sys.platform == "darwin":
01257                 bz2_extra_link_args = ('-Wl,-search_paths_first',)
01258             else:
01259                 bz2_extra_link_args = ()
01260             exts.append( Extension('bz2', ['bz2module.c'],
01261                                    libraries = ['bz2'],
01262                                    extra_link_args = bz2_extra_link_args) )
01263         else:
01264             missing.append('bz2')
01265 
01266         # Interface to the Expat XML parser
01267         #
01268         # Expat was written by James Clark and is now maintained by a group of
01269         # developers on SourceForge; see www.libexpat.org for more information.
01270         # The pyexpat module was written by Paul Prescod after a prototype by
01271         # Jack Jansen.  The Expat source is included in Modules/expat/.  Usage
01272         # of a system shared libexpat.so is possible with --with-system-expat
01273         # configure option.
01274         #
01275         # More information on Expat can be found at www.libexpat.org.
01276         #
01277         if '--with-system-expat' in sysconfig.get_config_var("CONFIG_ARGS"):
01278             expat_inc = []
01279             define_macros = []
01280             expat_lib = ['expat']
01281             expat_sources = []
01282         else:
01283             expat_inc = [os.path.join(os.getcwd(), srcdir, 'Modules', 'expat')]
01284             define_macros = [
01285                 ('HAVE_EXPAT_CONFIG_H', '1'),
01286             ]
01287             expat_lib = []
01288             expat_sources = ['expat/xmlparse.c',
01289                              'expat/xmlrole.c',
01290                              'expat/xmltok.c']
01291 
01292         exts.append(Extension('pyexpat',
01293                               define_macros = define_macros,
01294                               include_dirs = expat_inc,
01295                               libraries = expat_lib,
01296                               sources = ['pyexpat.c'] + expat_sources
01297                               ))
01298 
01299         # Fredrik Lundh's cElementTree module.  Note that this also
01300         # uses expat (via the CAPI hook in pyexpat).
01301 
01302         if os.path.isfile(os.path.join(srcdir, 'Modules', '_elementtree.c')):
01303             define_macros.append(('USE_PYEXPAT_CAPI', None))
01304             exts.append(Extension('_elementtree',
01305                                   define_macros = define_macros,
01306                                   include_dirs = expat_inc,
01307                                   libraries = expat_lib,
01308                                   sources = ['_elementtree.c'],
01309                                   ))
01310         else:
01311             missing.append('_elementtree')
01312 
01313         # Hye-Shik Chang's CJKCodecs modules.
01314         exts.append(Extension('_multibytecodec',
01315                               ['cjkcodecs/multibytecodec.c']))
01316         for loc in ('kr', 'jp', 'cn', 'tw', 'hk', 'iso2022'):
01317             exts.append(Extension('_codecs_%s' % loc,
01318                                   ['cjkcodecs/_codecs_%s.c' % loc]))
01319 
01320         # Thomas Heller's _ctypes module
01321         self.detect_ctypes(inc_dirs, lib_dirs)
01322 
01323         # Richard Oudkerk's multiprocessing module
01324         if platform == 'win32':             # Windows
01325             macros = dict()
01326             libraries = ['ws2_32']
01327 
01328         elif platform == 'darwin':          # Mac OSX
01329             macros = dict()
01330             libraries = []
01331 
01332         elif platform == 'cygwin':          # Cygwin
01333             macros = dict()
01334             libraries = []
01335 
01336         elif platform in ('freebsd4', 'freebsd5', 'freebsd6', 'freebsd7', 'freebsd8'):
01337             # FreeBSD's P1003.1b semaphore support is very experimental
01338             # and has many known problems. (as of June 2008)
01339             macros = dict()
01340             libraries = []
01341 
01342         elif platform.startswith('openbsd'):
01343             macros = dict()
01344             libraries = []
01345 
01346         elif platform.startswith('netbsd'):
01347             macros = dict()
01348             libraries = []
01349 
01350         else:                                   # Linux and other unices
01351             macros = dict()
01352             libraries = ['rt']
01353 
01354         if platform == 'win32':
01355             multiprocessing_srcs = [ '_multiprocessing/multiprocessing.c',
01356                                      '_multiprocessing/semaphore.c',
01357                                      '_multiprocessing/pipe_connection.c',
01358                                      '_multiprocessing/socket_connection.c',
01359                                      '_multiprocessing/win32_functions.c'
01360                                    ]
01361 
01362         else:
01363             multiprocessing_srcs = [ '_multiprocessing/multiprocessing.c',
01364                                      '_multiprocessing/socket_connection.c'
01365                                    ]
01366             if (sysconfig.get_config_var('HAVE_SEM_OPEN') and not
01367                 sysconfig.get_config_var('POSIX_SEMAPHORES_NOT_ENABLED')):
01368                 multiprocessing_srcs.append('_multiprocessing/semaphore.c')
01369 
01370         if sysconfig.get_config_var('WITH_THREAD'):
01371             exts.append ( Extension('_multiprocessing', multiprocessing_srcs,
01372                                     define_macros=list(macros.items()),
01373                                     include_dirs=["Modules/_multiprocessing"]))
01374         else:
01375             missing.append('_multiprocessing')
01376         # End multiprocessing
01377 
01378         # Platform-specific libraries
01379         if (platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
01380                         'freebsd7', 'freebsd8')
01381             or platform.startswith("gnukfreebsd")):
01382             exts.append( Extension('ossaudiodev', ['ossaudiodev.c']) )
01383         else:
01384             missing.append('ossaudiodev')
01385 
01386         if sys.platform == 'darwin':
01387             exts.append(
01388                        Extension('_gestalt', ['_gestalt.c'],
01389                        extra_link_args=['-framework', 'Carbon'])
01390                        )
01391             exts.append(
01392                        Extension('_scproxy', ['_scproxy.c'],
01393                        extra_link_args=[
01394                            '-framework', 'SystemConfiguration',
01395                            '-framework', 'CoreFoundation',
01396                         ]))
01397 
01398         self.extensions.extend(exts)
01399 
01400         # Call the method for detecting whether _tkinter can be compiled
01401         self.detect_tkinter(inc_dirs, lib_dirs)
01402 
01403         if '_tkinter' not in [e.name for e in self.extensions]:
01404             missing.append('_tkinter')
01405 
01406         return missing

Here is the call graph for this function:

Here is the caller graph for this function:

def setup.PyBuildExt.detect_tkinter (   self,
  inc_dirs,
  lib_dirs 
)

Definition at line 1497 of file setup.py.

01497 
01498     def detect_tkinter(self, inc_dirs, lib_dirs):
01499         # The _tkinter module.
01500 
01501         # Rather than complicate the code below, detecting and building
01502         # AquaTk is a separate method. Only one Tkinter will be built on
01503         # Darwin - either AquaTk, if it is found, or X11 based Tk.
01504         platform = self.get_platform()
01505         if (platform == 'darwin' and
01506             self.detect_tkinter_darwin(inc_dirs, lib_dirs)):
01507             return
01508 
01509         # Assume we haven't found any of the libraries or include files
01510         # The versions with dots are used on Unix, and the versions without
01511         # dots on Windows, for detection by cygwin.
01512         tcllib = tklib = tcl_includes = tk_includes = None
01513         for version in ['8.6', '86', '8.5', '85', '8.4', '84', '8.3', '83',
01514                         '8.2', '82', '8.1', '81', '8.0', '80']:
01515             tklib = self.compiler.find_library_file(lib_dirs,
01516                                                         'tk' + version)
01517             tcllib = self.compiler.find_library_file(lib_dirs,
01518                                                          'tcl' + version)
01519             if tklib and tcllib:
01520                 # Exit the loop when we've found the Tcl/Tk libraries
01521                 break
01522 
01523         # Now check for the header files
01524         if tklib and tcllib:
01525             # Check for the include files on Debian and {Free,Open}BSD, where
01526             # they're put in /usr/include/{tcl,tk}X.Y
01527             dotversion = version
01528             if '.' not in dotversion and "bsd" in sys.platform.lower():
01529                 # OpenBSD and FreeBSD use Tcl/Tk library names like libtcl83.a,
01530                 # but the include subdirs are named like .../include/tcl8.3.
01531                 dotversion = dotversion[:-1] + '.' + dotversion[-1]
01532             tcl_include_sub = []
01533             tk_include_sub = []
01534             for dir in inc_dirs:
01535                 tcl_include_sub += [dir + os.sep + "tcl" + dotversion]
01536                 tk_include_sub += [dir + os.sep + "tk" + dotversion]
01537             tk_include_sub += tcl_include_sub
01538             tcl_includes = find_file('tcl.h', inc_dirs, tcl_include_sub)
01539             tk_includes = find_file('tk.h', inc_dirs, tk_include_sub)
01540 
01541         if (tcllib is None or tklib is None or
01542             tcl_includes is None or tk_includes is None):
01543             self.announce("INFO: Can't locate Tcl/Tk libs and/or headers", 2)
01544             return
01545 
01546         # OK... everything seems to be present for Tcl/Tk.
01547 
01548         include_dirs = [] ; libs = [] ; defs = [] ; added_lib_dirs = []
01549         for dir in tcl_includes + tk_includes:
01550             if dir not in include_dirs:
01551                 include_dirs.append(dir)
01552 
01553         # Check for various platform-specific directories
01554         if platform == 'sunos5':
01555             include_dirs.append('/usr/openwin/include')
01556             added_lib_dirs.append('/usr/openwin/lib')
01557         elif os.path.exists('/usr/X11R6/include'):
01558             include_dirs.append('/usr/X11R6/include')
01559             added_lib_dirs.append('/usr/X11R6/lib64')
01560             added_lib_dirs.append('/usr/X11R6/lib')
01561         elif os.path.exists('/usr/X11R5/include'):
01562             include_dirs.append('/usr/X11R5/include')
01563             added_lib_dirs.append('/usr/X11R5/lib')
01564         else:
01565             # Assume default location for X11
01566             include_dirs.append('/usr/X11/include')
01567             added_lib_dirs.append('/usr/X11/lib')
01568 
01569         # If Cygwin, then verify that X is installed before proceeding
01570         if platform == 'cygwin':
01571             x11_inc = find_file('X11/Xlib.h', [], include_dirs)
01572             if x11_inc is None:
01573                 return
01574 
01575         # Check for BLT extension
01576         if self.compiler.find_library_file(lib_dirs + added_lib_dirs,
01577                                                'BLT8.0'):
01578             defs.append( ('WITH_BLT', 1) )
01579             libs.append('BLT8.0')
01580         elif self.compiler.find_library_file(lib_dirs + added_lib_dirs,
01581                                                 'BLT'):
01582             defs.append( ('WITH_BLT', 1) )
01583             libs.append('BLT')
01584 
01585         # Add the Tcl/Tk libraries
01586         libs.append('tk'+ version)
01587         libs.append('tcl'+ version)
01588 
01589         if platform in ['aix3', 'aix4']:
01590             libs.append('ld')
01591 
01592         # Finally, link with the X11 libraries (not appropriate on cygwin)
01593         if platform != "cygwin":
01594             libs.append('X11')
01595 
01596         ext = Extension('_tkinter', ['_tkinter.c', 'tkappinit.c'],
01597                         define_macros=[('WITH_APPINIT', 1)] + defs,
01598                         include_dirs = include_dirs,
01599                         libraries = libs,
01600                         library_dirs = added_lib_dirs,
01601                         )
01602         self.extensions.append(ext)

Here is the call graph for this function:

Here is the caller graph for this function:

def setup.PyBuildExt.detect_tkinter_darwin (   self,
  inc_dirs,
  lib_dirs 
)

Definition at line 1407 of file setup.py.

01407 
01408     def detect_tkinter_darwin(self, inc_dirs, lib_dirs):
01409         # The _tkinter module, using frameworks. Since frameworks are quite
01410         # different the UNIX search logic is not sharable.
01411         from os.path import join, exists
01412         framework_dirs = [
01413             '/Library/Frameworks',
01414             '/System/Library/Frameworks/',
01415             join(os.getenv('HOME'), '/Library/Frameworks')
01416         ]
01417 
01418         sysroot = macosx_sdk_root()
01419 
01420         # Find the directory that contains the Tcl.framework and Tk.framework
01421         # bundles.
01422         # XXX distutils should support -F!
01423         for F in framework_dirs:
01424             # both Tcl.framework and Tk.framework should be present
01425 
01426 
01427             for fw in 'Tcl', 'Tk':
01428                 if is_macosx_sdk_path(F):
01429                     if not exists(join(sysroot, F[1:], fw + '.framework')):
01430                         break
01431                 else:
01432                     if not exists(join(F, fw + '.framework')):
01433                         break
01434             else:
01435                 # ok, F is now directory with both frameworks. Continure
01436                 # building
01437                 break
01438         else:
01439             # Tk and Tcl frameworks not found. Normal "unix" tkinter search
01440             # will now resume.
01441             return 0
01442 
01443         # For 8.4a2, we must add -I options that point inside the Tcl and Tk
01444         # frameworks. In later release we should hopefully be able to pass
01445         # the -F option to gcc, which specifies a framework lookup path.
01446         #
01447         include_dirs = [
01448             join(F, fw + '.framework', H)
01449             for fw in ('Tcl', 'Tk')
01450             for H in ('Headers', 'Versions/Current/PrivateHeaders')
01451         ]
01452 
01453         # For 8.4a2, the X11 headers are not included. Rather than include a
01454         # complicated search, this is a hard-coded path. It could bail out
01455         # if X11 libs are not found...
01456         include_dirs.append('/usr/X11R6/include')
01457         frameworks = ['-framework', 'Tcl', '-framework', 'Tk']
01458 
01459         # All existing framework builds of Tcl/Tk don't support 64-bit
01460         # architectures.
01461         cflags = sysconfig.get_config_vars('CFLAGS')[0]
01462         archs = re.findall('-arch\s+(\w+)', cflags)
01463 
01464         tmpfile = os.path.join(self.build_temp, 'tk.arch')
01465         if not os.path.exists(self.build_temp):
01466             os.makedirs(self.build_temp)
01467 
01468         # Note: cannot use os.popen or subprocess here, that
01469         # requires extensions that are not available here.
01470         if is_macosx_sdk_path(F):
01471             os.system("file %s/Tk.framework/Tk | grep 'for architecture' > %s"%(os.path.join(sysroot, F[1:]), tmpfile))
01472         else:
01473             os.system("file %s/Tk.framework/Tk | grep 'for architecture' > %s"%(F, tmpfile))
01474 
01475         with open(tmpfile) as fp:
01476             detected_archs = []
01477             for ln in fp:
01478                 a = ln.split()[-1]
01479                 if a in archs:
01480                     detected_archs.append(ln.split()[-1])
01481         os.unlink(tmpfile)
01482 
01483         for a in detected_archs:
01484             frameworks.append('-arch')
01485             frameworks.append(a)
01486 
01487         ext = Extension('_tkinter', ['_tkinter.c', 'tkappinit.c'],
01488                         define_macros=[('WITH_APPINIT', 1)],
01489                         include_dirs = include_dirs,
01490                         libraries = [],
01491                         extra_compile_args = frameworks[2:],
01492                         extra_link_args = frameworks,
01493                         )
01494         self.extensions.append(ext)
01495         return 1
01496 

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 136 of file build_ext.py.

00136 
00137     def finalize_options(self):
00138         from distutils import sysconfig
00139 
00140         self.set_undefined_options('build',
00141                                    ('build_lib', 'build_lib'),
00142                                    ('build_temp', 'build_temp'),
00143                                    ('compiler', 'compiler'),
00144                                    ('debug', 'debug'),
00145                                    ('force', 'force'),
00146                                    ('plat_name', 'plat_name'),
00147                                    )
00148 
00149         if self.package is None:
00150             self.package = self.distribution.ext_package
00151 
00152         self.extensions = self.distribution.ext_modules
00153 
00154         # Make sure Python's include directories (for Python.h, pyconfig.h,
00155         # etc.) are in the include search path.
00156         py_include = sysconfig.get_python_inc()
00157         plat_py_include = sysconfig.get_python_inc(plat_specific=1)
00158         if self.include_dirs is None:
00159             self.include_dirs = self.distribution.include_dirs or []
00160         if isinstance(self.include_dirs, str):
00161             self.include_dirs = self.include_dirs.split(os.pathsep)
00162 
00163         # Put the Python "system" include dir at the end, so that
00164         # any local include dirs take precedence.
00165         self.include_dirs.append(py_include)
00166         if plat_py_include != py_include:
00167             self.include_dirs.append(plat_py_include)
00168 
00169         if isinstance(self.libraries, str):
00170             self.libraries = [self.libraries]
00171 
00172         # Life is easier if we're not forever checking for None, so
00173         # simplify these options to empty lists if unset
00174         if self.libraries is None:
00175             self.libraries = []
00176         if self.library_dirs is None:
00177             self.library_dirs = []
00178         elif isinstance(self.library_dirs, str):
00179             self.library_dirs = self.library_dirs.split(os.pathsep)
00180 
00181         if self.rpath is None:
00182             self.rpath = []
00183         elif isinstance(self.rpath, str):
00184             self.rpath = self.rpath.split(os.pathsep)
00185 
00186         # for extensions under windows use different directories
00187         # for Release and Debug builds.
00188         # also Python's library directory must be appended to library_dirs
00189         if os.name == 'nt':
00190             # the 'libs' directory is for binary installs - we assume that
00191             # must be the *native* platform.  But we don't really support
00192             # cross-compiling via a binary install anyway, so we let it go.
00193             self.library_dirs.append(os.path.join(sys.exec_prefix, 'libs'))
00194             if self.debug:
00195                 self.build_temp = os.path.join(self.build_temp, "Debug")
00196             else:
00197                 self.build_temp = os.path.join(self.build_temp, "Release")
00198 
00199             # Append the source distribution include and library directories,
00200             # this allows distutils on windows to work in the source tree
00201             self.include_dirs.append(os.path.join(sys.exec_prefix, 'PC'))
00202             if MSVC_VERSION == 9:
00203                 # Use the .lib files for the correct architecture
00204                 if self.plat_name == 'win32':
00205                     suffix = ''
00206                 else:
00207                     # win-amd64 or win-ia64
00208                     suffix = self.plat_name[4:]
00209                 new_lib = os.path.join(sys.exec_prefix, 'PCbuild')
00210                 if suffix:
00211                     new_lib = os.path.join(new_lib, suffix)
00212                 self.library_dirs.append(new_lib)
00213 
00214             elif MSVC_VERSION == 8:
00215                 self.library_dirs.append(os.path.join(sys.exec_prefix,
00216                                          'PC', 'VS8.0'))
00217             elif MSVC_VERSION == 7:
00218                 self.library_dirs.append(os.path.join(sys.exec_prefix,
00219                                          'PC', 'VS7.1'))
00220             else:
00221                 self.library_dirs.append(os.path.join(sys.exec_prefix,
00222                                          'PC', 'VC6'))
00223 
00224         # OS/2 (EMX) doesn't support Debug vs Release builds, but has the
00225         # import libraries in its "Config" subdirectory
00226         if os.name == 'os2':
00227             self.library_dirs.append(os.path.join(sys.exec_prefix, 'Config'))
00228 
00229         # for extensions under Cygwin and AtheOS Python's library directory must be
00230         # appended to library_dirs
00231         if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos':
00232             if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")):
00233                 # building third party extensions
00234                 self.library_dirs.append(os.path.join(sys.prefix, "lib",
00235                                                       "python" + get_python_version(),
00236                                                       "config"))
00237             else:
00238                 # building python standard extensions
00239                 self.library_dirs.append('.')
00240 
00241         # for extensions under Linux or Solaris with a shared Python library,
00242         # Python's library directory must be appended to library_dirs
00243         sysconfig.get_config_var('Py_ENABLE_SHARED')
00244         if ((sys.platform.startswith('linux') or sys.platform.startswith('gnu')
00245              or sys.platform.startswith('sunos'))
00246             and sysconfig.get_config_var('Py_ENABLE_SHARED')):
00247             if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")):
00248                 # building third party extensions
00249                 self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))
00250             else:
00251                 # building python standard extensions
00252                 self.library_dirs.append('.')
00253 
00254         # The argument parsing will result in self.define being a string, but
00255         # it has to be a list of 2-tuples.  All the preprocessor symbols
00256         # specified by the 'define' option will be set to '1'.  Multiple
00257         # symbols can be separated with commas.
00258 
00259         if self.define:
00260             defines = self.define.split(',')
00261             self.define = [(symbol, '1') for symbol in defines]
00262 
00263         # The option for macros to undefine is also a string from the
00264         # option parsing, but has to be a list.  Multiple symbols can also
00265         # be separated with commas here.
00266         if self.undef:
00267             self.undef = self.undef.split(',')
00268 
00269         if self.swig_opts is None:
00270             self.swig_opts = []
00271         else:
00272             self.swig_opts = self.swig_opts.split(' ')
00273 
00274         # Finally add the user include and library directories if requested
00275         if self.user:
00276             user_include = os.path.join(USER_BASE, "include")
00277             user_lib = os.path.join(USER_BASE, "lib")
00278             if os.path.isdir(user_include):
00279                 self.include_dirs.append(user_include)
00280             if os.path.isdir(user_lib):
00281                 self.library_dirs.append(user_lib)
00282                 self.rpath.append(user_lib)

Here is the call graph for this function:

Here is the caller graph for this function:

Return the name of the SWIG executable.  On Unix, this is
just "swig" -- it should be in the PATH.  Tries a bit harder on
Windows.

Definition at line 597 of file build_ext.py.

00597 
00598     def find_swig(self):
00599         """Return the name of the SWIG executable.  On Unix, this is
00600         just "swig" -- it should be in the PATH.  Tries a bit harder on
00601         Windows.
00602         """
00603         if os.name == "posix":
00604             return "swig"
00605         elif os.name == "nt":
00606             # Look for SWIG in its standard installation directory on
00607             # Windows (or so I presume!).  If we find it there, great;
00608             # if not, act like Unix and assume it's in the PATH.
00609             for vers in ("1.3", "1.2", "1.1"):
00610                 fn = os.path.join("c:\\swig%s" % vers, "swig.exe")
00611                 if os.path.isfile(fn):
00612                     return fn
00613             else:
00614                 return "swig.exe"
00615         elif os.name == "os2":
00616             # assume swig available in the PATH.
00617             return "swig.exe"
00618         else:
00619             raise DistutilsPlatformError(
00620                   "I don't know how to find (much less run) SWIG "
00621                   "on platform '%s'" % os.name)

Here is the caller graph for this function:

def distutils.command.build_ext.build_ext.get_export_symbols (   self,
  ext 
) [inherited]
Return the list of symbols that a shared extension has to
export.  This either uses 'ext.export_symbols' or, if it's not
provided, "PyInit_" + module_name.  Only relevant on Windows, where
the .pyd file (DLL) must export the module "PyInit_" function.

Definition at line 676 of file build_ext.py.

00676 
00677     def get_export_symbols(self, ext):
00678         """Return the list of symbols that a shared extension has to
00679         export.  This either uses 'ext.export_symbols' or, if it's not
00680         provided, "PyInit_" + module_name.  Only relevant on Windows, where
00681         the .pyd file (DLL) must export the module "PyInit_" function.
00682         """
00683         initfunc_name = "PyInit_" + ext.name.split('.')[-1]
00684         if initfunc_name not in ext.export_symbols:
00685             ext.export_symbols.append(initfunc_name)
00686         return ext.export_symbols

def distutils.command.build_ext.build_ext.get_ext_filename (   self,
  ext_name 
) [inherited]

Definition at line 660 of file build_ext.py.

00660 
00661     def get_ext_filename(self, ext_name):
00662         r"""Convert the name of an extension (eg. "foo.bar") into the name
00663         of the file from which it will be loaded (eg. "foo/bar.so", or
00664         "foo\bar.pyd").
00665         """
00666         from distutils.sysconfig import get_config_var
00667         ext_path = ext_name.split('.')
00668         # OS/2 has an 8 character module (extension) limit :-(
00669         if os.name == "os2":
00670             ext_path[len(ext_path) - 1] = ext_path[len(ext_path) - 1][:8]
00671         # extensions in debug_mode are named 'module_d.pyd' under windows
00672         so_ext = get_config_var('SO')
00673         if os.name == 'nt' and self.debug:
00674             return os.path.join(*ext_path) + '_d' + so_ext
00675         return os.path.join(*ext_path) + so_ext

Here is the call graph for this function:

Here is the caller graph for this function:

def distutils.command.build_ext.build_ext.get_ext_fullname (   self,
  ext_name 
) [inherited]
Returns the fullname of a given extension name.

Adds the `package.` prefix

Definition at line 651 of file build_ext.py.

00651 
00652     def get_ext_fullname(self, ext_name):
00653         """Returns the fullname of a given extension name.
00654 
00655         Adds the `package.` prefix"""
00656         if self.package is None:
00657             return ext_name
00658         else:
00659             return self.package + '.' + ext_name

Here is the caller graph for this function:

def distutils.command.build_ext.build_ext.get_ext_fullpath (   self,
  ext_name 
) [inherited]
Returns the path of the filename for a given extension.

The file is located in `build_lib` or directly in the package
(inplace option).

Definition at line 624 of file build_ext.py.

00624 
00625     def get_ext_fullpath(self, ext_name):
00626         """Returns the path of the filename for a given extension.
00627 
00628         The file is located in `build_lib` or directly in the package
00629         (inplace option).
00630         """
00631         fullname = self.get_ext_fullname(ext_name)
00632         modpath = fullname.split('.')
00633         filename = self.get_ext_filename(modpath[-1])
00634 
00635         if not self.inplace:
00636             # no further work needed
00637             # returning :
00638             #   build_dir/package/path/filename
00639             filename = os.path.join(*modpath[:-1]+[filename])
00640             return os.path.join(self.build_lib, filename)
00641 
00642         # the inplace option requires to find the package directory
00643         # using the build_py command for that
00644         package = '.'.join(modpath[0:-1])
00645         build_py = self.get_finalized_command('build_py')
00646         package_dir = os.path.abspath(build_py.get_package_dir(package))
00647 
00648         # returning
00649         #   package_dir/filename
00650         return os.path.join(package_dir, filename)

Here is the call graph for this function:

Here is the caller graph for this function:

def distutils.command.build_ext.build_ext.get_libraries (   self,
  ext 
) [inherited]
Return the list of libraries to link against when building a
shared extension.  On most platforms, this is just 'ext.libraries';
on Windows and OS/2, we add the Python library (eg. python20.dll).

Definition at line 687 of file build_ext.py.

00687 
00688     def get_libraries(self, ext):
00689         """Return the list of libraries to link against when building a
00690         shared extension.  On most platforms, this is just 'ext.libraries';
00691         on Windows and OS/2, we add the Python library (eg. python20.dll).
00692         """
00693         # The python library is always needed on Windows.  For MSVC, this
00694         # is redundant, since the library is mentioned in a pragma in
00695         # pyconfig.h that MSVC groks.  The other Windows compilers all seem
00696         # to need it mentioned explicitly, though, so that's what we do.
00697         # Append '_d' to the python import library on debug builds.
00698         if sys.platform == "win32":
00699             from distutils.msvccompiler import MSVCCompiler
00700             if not isinstance(self.compiler, MSVCCompiler):
00701                 template = "python%d%d"
00702                 if self.debug:
00703                     template = template + '_d'
00704                 pythonlib = (template %
00705                        (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
00706                 # don't extend ext.libraries, it may be shared with other
00707                 # extensions, it is a reference to the original list
00708                 return ext.libraries + [pythonlib]
00709             else:
00710                 return ext.libraries
00711         elif sys.platform == "os2emx":
00712             # EMX/GCC requires the python library explicitly, and I
00713             # believe VACPP does as well (though not confirmed) - AIM Apr01
00714             template = "python%d%d"
00715             # debug versions of the main DLL aren't supported, at least
00716             # not at this time - AIM Apr01
00717             #if self.debug:
00718             #    template = template + '_d'
00719             pythonlib = (template %
00720                    (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
00721             # don't extend ext.libraries, it may be shared with other
00722             # extensions, it is a reference to the original list
00723             return ext.libraries + [pythonlib]
00724         elif sys.platform[:6] == "cygwin":
00725             template = "python%d.%d"
00726             pythonlib = (template %
00727                    (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
00728             # don't extend ext.libraries, it may be shared with other
00729             # extensions, it is a reference to the original list
00730             return ext.libraries + [pythonlib]
00731         elif sys.platform[:6] == "atheos":
00732             from distutils import sysconfig
00733 
00734             template = "python%d.%d"
00735             pythonlib = (template %
00736                    (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
00737             # Get SHLIBS from Makefile
00738             extra = []
00739             for lib in sysconfig.get_config_var('SHLIBS').split():
00740                 if lib.startswith('-l'):
00741                     extra.append(lib[2:])
00742                 else:
00743                     extra.append(lib)
00744             # don't extend ext.libraries, it may be shared with other
00745             # extensions, it is a reference to the original list
00746             return ext.libraries + [pythonlib, "m"] + extra
00747         elif sys.platform == 'darwin':
00748             # Don't use the default code below
00749             return ext.libraries
00750         elif sys.platform[:3] == 'aix':
00751             # Don't use the default code below
00752             return ext.libraries
00753         else:
00754             from distutils import sysconfig
00755             if sysconfig.get_config_var('Py_ENABLE_SHARED'):
00756                 pythonlib = 'python{}.{}{}'.format(
00757                     sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff,
00758                     sys.abiflags)
00759                 return ext.libraries + [pythonlib]
00760             else:
00761                 return ext.libraries

Here is the call graph for this function:

Definition at line 434 of file build_ext.py.

00434 
00435     def get_outputs(self):
00436         # Sanity check the 'extensions' list -- can't assume this is being
00437         # done in the same run as a 'build_extensions()' call (in fact, we
00438         # can probably assume that it *isn't*!).
00439         self.check_extensions_list(self.extensions)
00440 
00441         # And build the list of output (built) filenames.  Note that this
00442         # ignores the 'inplace' flag, and assumes everything goes in the
00443         # "build" tree.
00444         outputs = []
00445         for ext in self.extensions:
00446             outputs.append(self.get_ext_fullpath(ext.name))
00447         return outputs

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 366 of file setup.py.

00366 
00367     def get_platform(self):
00368         # Get value of sys.platform
00369         for platform in ['cygwin', 'darwin', 'osf1']:
00370             if sys.platform.startswith(platform):
00371                 return platform
00372         return sys.platform

Here is the caller graph for this function:

Definition at line 425 of file build_ext.py.

00425 
00426     def get_source_files(self):
00427         self.check_extensions_list(self.extensions)
00428         filenames = []
00429 
00430         # Wouldn't it be neat if we knew the names of header files too...
00431         for ext in self.extensions:
00432             filenames.extend(ext.sources)
00433         return filenames

Here is the call graph for this function:

Definition at line 113 of file build_ext.py.

00113 
00114     def initialize_options(self):
00115         self.extensions = None
00116         self.build_lib = None
00117         self.plat_name = None
00118         self.build_temp = None
00119         self.inplace = 0
00120         self.package = None
00121 
00122         self.include_dirs = None
00123         self.define = None
00124         self.undef = None
00125         self.libraries = None
00126         self.library_dirs = None
00127         self.rpath = None
00128         self.link_objects = None
00129         self.debug = None
00130         self.force = None
00131         self.compiler = None
00132         self.swig = None
00133         self.swig_cpp = None
00134         self.swig_opts = None
00135         self.user = None

def distutils.command.build_ext.build_ext.run (   self) [inherited]

Definition at line 283 of file build_ext.py.

00283 
00284     def run(self):
00285         from distutils.ccompiler import new_compiler
00286 
00287         # 'self.extensions', as supplied by setup.py, is a list of
00288         # Extension instances.  See the documentation for Extension (in
00289         # distutils.extension) for details.
00290         #
00291         # For backwards compatibility with Distutils 0.8.2 and earlier, we
00292         # also allow the 'extensions' list to be a list of tuples:
00293         #    (ext_name, build_info)
00294         # where build_info is a dictionary containing everything that
00295         # Extension instances do except the name, with a few things being
00296         # differently named.  We convert these 2-tuples to Extension
00297         # instances as needed.
00298 
00299         if not self.extensions:
00300             return
00301 
00302         # If we were asked to build any C/C++ libraries, make sure that the
00303         # directory where we put them is in the library search path for
00304         # linking extensions.
00305         if self.distribution.has_c_libraries():
00306             build_clib = self.get_finalized_command('build_clib')
00307             self.libraries.extend(build_clib.get_library_names() or [])
00308             self.library_dirs.append(build_clib.build_clib)
00309 
00310         # Setup the CCompiler object that we'll use to do all the
00311         # compiling and linking
00312         self.compiler = new_compiler(compiler=self.compiler,
00313                                      verbose=self.verbose,
00314                                      dry_run=self.dry_run,
00315                                      force=self.force)
00316         customize_compiler(self.compiler)
00317         # If we are cross-compiling, init the compiler now (if we are not
00318         # cross-compiling, init would not hurt, but people may rely on
00319         # late initialization of compiler even if they shouldn't...)
00320         if os.name == 'nt' and self.plat_name != get_platform():
00321             self.compiler.initialize(self.plat_name)
00322 
00323         # And make sure that any compile/link-related options (which might
00324         # come from the command-line or from the setup script) are set in
00325         # that CCompiler object -- that way, they automatically apply to
00326         # all compiling and linking done here.
00327         if self.include_dirs is not None:
00328             self.compiler.set_include_dirs(self.include_dirs)
00329         if self.define is not None:
00330             # 'define' option is a list of (name,value) tuples
00331             for (name, value) in self.define:
00332                 self.compiler.define_macro(name, value)
00333         if self.undef is not None:
00334             for macro in self.undef:
00335                 self.compiler.undefine_macro(macro)
00336         if self.libraries is not None:
00337             self.compiler.set_libraries(self.libraries)
00338         if self.library_dirs is not None:
00339             self.compiler.set_library_dirs(self.library_dirs)
00340         if self.rpath is not None:
00341             self.compiler.set_runtime_library_dirs(self.rpath)
00342         if self.link_objects is not None:
00343             self.compiler.set_link_objects(self.link_objects)
00344 
00345         # Now actually compile and link everything.
00346         self.build_extensions()

Here is the call graph for this function:

Here is the caller graph for this function:

def distutils.command.build_ext.build_ext.swig_sources (   self,
  sources,
  extension 
) [inherited]
Walk the list of source files in 'sources', looking for SWIG
interface (.i) files.  Run SWIG on all that are found, and
return a modified 'sources' list with SWIG source files replaced
by the generated C (or C++) files.

Definition at line 543 of file build_ext.py.

00543 
00544     def swig_sources(self, sources, extension):
00545         """Walk the list of source files in 'sources', looking for SWIG
00546         interface (.i) files.  Run SWIG on all that are found, and
00547         return a modified 'sources' list with SWIG source files replaced
00548         by the generated C (or C++) files.
00549         """
00550         new_sources = []
00551         swig_sources = []
00552         swig_targets = {}
00553 
00554         # XXX this drops generated C/C++ files into the source tree, which
00555         # is fine for developers who want to distribute the generated
00556         # source -- but there should be an option to put SWIG output in
00557         # the temp dir.
00558 
00559         if self.swig_cpp:
00560             log.warn("--swig-cpp is deprecated - use --swig-opts=-c++")
00561 
00562         if self.swig_cpp or ('-c++' in self.swig_opts) or \
00563            ('-c++' in extension.swig_opts):
00564             target_ext = '.cpp'
00565         else:
00566             target_ext = '.c'
00567 
00568         for source in sources:
00569             (base, ext) = os.path.splitext(source)
00570             if ext == ".i":             # SWIG interface file
00571                 new_sources.append(base + '_wrap' + target_ext)
00572                 swig_sources.append(source)
00573                 swig_targets[source] = new_sources[-1]
00574             else:
00575                 new_sources.append(source)
00576 
00577         if not swig_sources:
00578             return new_sources
00579 
00580         swig = self.swig or self.find_swig()
00581         swig_cmd = [swig, "-python"]
00582         swig_cmd.extend(self.swig_opts)
00583         if self.swig_cpp:
00584             swig_cmd.append("-c++")
00585 
00586         # Do not override commandline arguments
00587         if not self.swig_opts:
00588             for o in extension.swig_opts:
00589                 swig_cmd.append(o)
00590 
00591         for source in swig_sources:
00592             target = swig_targets[source]
00593             log.info("swigging %s to %s", source, target)
00594             self.spawn(swig_cmd + ["-o", target, source])
00595 
00596         return new_sources

Here is the call graph for this function:

Here is the caller graph for this function:


Member Data Documentation

list distutils.command.build_ext.build_ext.boolean_options = ['inplace', 'debug', 'force', 'swig-cpp'] [static, inherited]

Definition at line 101 of file build_ext.py.

Definition at line 115 of file build_ext.py.

Definition at line 117 of file build_ext.py.

Definition at line 130 of file build_ext.py.

Definition at line 128 of file build_ext.py.

Definition at line 122 of file build_ext.py.

string distutils.command.build_ext.build_ext.description = "build C/C++ extensions (compile/link to build directory)" [static, inherited]

Definition at line 41 of file build_ext.py.

Reimplemented from distutils.command.build_ext.build_ext.

Definition at line 180 of file setup.py.

Definition at line 159 of file setup.py.

Definition at line 129 of file build_ext.py.

Initial value:
[
        ('help-compiler', None,
         "list available compilers", show_compilers),
        ]

Definition at line 108 of file build_ext.py.

Definition at line 121 of file build_ext.py.

Definition at line 118 of file build_ext.py.

Definition at line 124 of file build_ext.py.

Definition at line 125 of file build_ext.py.

Definition at line 127 of file build_ext.py.

Definition at line 119 of file build_ext.py.

Definition at line 116 of file build_ext.py.

Definition at line 126 of file build_ext.py.

string distutils.command.build_ext.build_ext.sep_by = " (separated by '%s')" [static, inherited]

Definition at line 61 of file build_ext.py.

Definition at line 131 of file build_ext.py.

Definition at line 132 of file build_ext.py.

Definition at line 133 of file build_ext.py.

Definition at line 123 of file build_ext.py.

Definition at line 134 of file build_ext.py.

Definition at line 62 of file build_ext.py.


The documentation for this class was generated from the following file: