ยปCore Development>Code coverage>setup.py

Python code coverage for setup.py

#countcontent
1n/a# Autodetecting setup.py script for building the Python extensions
2n/a#
3n/a
4n/a__version__ = "$Revision: 78784 $"
5n/a
6n/aimport sys, os, imp, re, optparse
7n/afrom glob import glob
8n/afrom platform import machine as platform_machine
9n/aimport sysconfig
10n/a
11n/afrom distutils import log
12n/afrom distutils import text_file
13n/afrom distutils.errors import *
14n/afrom distutils.core import Extension, setup
15n/afrom distutils.command.build_ext import build_ext
16n/afrom distutils.command.install import install
17n/afrom distutils.command.install_lib import install_lib
18n/a
19n/a# Were we compiled --with-pydebug or with #define Py_DEBUG?
20n/aCOMPILED_WITH_PYDEBUG = hasattr(sys, 'gettotalrefcount')
21n/a
22n/a# This global variable is used to hold the list of modules to be disabled.
23n/adisabled_module_list = []
24n/a
25n/adef add_dir_to_list(dirlist, dir):
26n/a """Add the directory 'dir' to the list 'dirlist' (at the front) if
27n/a 1) 'dir' is not already in 'dirlist'
28n/a 2) 'dir' actually exists, and is a directory."""
29n/a if dir is not None and os.path.isdir(dir) and dir not in dirlist:
30n/a dirlist.insert(0, dir)
31n/a
32n/adef find_file(filename, std_dirs, paths):
33n/a """Searches for the directory where a given file is located,
34n/a and returns a possibly-empty list of additional directories, or None
35n/a if the file couldn't be found at all.
36n/a
37n/a 'filename' is the name of a file, such as readline.h or libcrypto.a.
38n/a 'std_dirs' is the list of standard system directories; if the
39n/a file is found in one of them, no additional directives are needed.
40n/a 'paths' is a list of additional locations to check; if the file is
41n/a found in one of them, the resulting list will contain the directory.
42n/a """
43n/a
44n/a # Check the standard locations
45n/a for dir in std_dirs:
46n/a f = os.path.join(dir, filename)
47n/a if os.path.exists(f): return []
48n/a
49n/a # Check the additional directories
50n/a for dir in paths:
51n/a f = os.path.join(dir, filename)
52n/a if os.path.exists(f):
53n/a return [dir]
54n/a
55n/a # Not found anywhere
56n/a return None
57n/a
58n/adef find_library_file(compiler, libname, std_dirs, paths):
59n/a result = compiler.find_library_file(std_dirs + paths, libname)
60n/a if result is None:
61n/a return None
62n/a
63n/a # Check whether the found file is in one of the standard directories
64n/a dirname = os.path.dirname(result)
65n/a for p in std_dirs:
66n/a # Ensure path doesn't end with path separator
67n/a p = p.rstrip(os.sep)
68n/a if p == dirname:
69n/a return [ ]
70n/a
71n/a # Otherwise, it must have been in one of the additional directories,
72n/a # so we have to figure out which one.
73n/a for p in paths:
74n/a # Ensure path doesn't end with path separator
75n/a p = p.rstrip(os.sep)
76n/a if p == dirname:
77n/a return [p]
78n/a else:
79n/a assert False, "Internal error: Path not found in std_dirs or paths"
80n/a
81n/adef module_enabled(extlist, modname):
82n/a """Returns whether the module 'modname' is present in the list
83n/a of extensions 'extlist'."""
84n/a extlist = [ext for ext in extlist if ext.name == modname]
85n/a return len(extlist)
86n/a
87n/adef find_module_file(module, dirlist):
88n/a """Find a module in a set of possible folders. If it is not found
89n/a return the unadorned filename"""
90n/a list = find_file(module, [], dirlist)
91n/a if not list:
92n/a return module
93n/a if len(list) > 1:
94n/a log.info("WARNING: multiple copies of %s found"%module)
95n/a return os.path.join(list[0], module)
96n/a
97n/aclass PyBuildExt(build_ext):
98n/a
99n/a def __init__(self, dist):
100n/a build_ext.__init__(self, dist)
101n/a self.failed = []
102n/a
103n/a def build_extensions(self):
104n/a
105n/a # Detect which modules should be compiled
106n/a missing = self.detect_modules()
107n/a
108n/a # Remove modules that are present on the disabled list
109n/a extensions = [ext for ext in self.extensions
110n/a if ext.name not in disabled_module_list]
111n/a # move ctypes to the end, it depends on other modules
112n/a ext_map = dict((ext.name, i) for i, ext in enumerate(extensions))
113n/a if "_ctypes" in ext_map:
114n/a ctypes = extensions.pop(ext_map["_ctypes"])
115n/a extensions.append(ctypes)
116n/a self.extensions = extensions
117n/a
118n/a # Fix up the autodetected modules, prefixing all the source files
119n/a # with Modules/ and adding Python's include directory to the path.
120n/a (srcdir,) = sysconfig.get_config_vars('srcdir')
121n/a if not srcdir:
122n/a # Maybe running on Windows but not using CYGWIN?
123n/a raise ValueError("No source directory; cannot proceed.")
124n/a srcdir = os.path.abspath(srcdir)
125n/a moddirlist = [os.path.join(srcdir, 'Modules')]
126n/a
127n/a # Platform-dependent module source and include directories
128n/a incdirlist = []
129n/a platform = self.get_platform()
130n/a if platform in ('darwin', 'mac') and ("--disable-toolbox-glue" not in
131n/a sysconfig.get_config_var("CONFIG_ARGS")):
132n/a # Mac OS X also includes some mac-specific modules
133n/a macmoddir = os.path.join(srcdir, 'Mac/Modules')
134n/a moddirlist.append(macmoddir)
135n/a incdirlist.append(os.path.join(srcdir, 'Mac/Include'))
136n/a
137n/a # Fix up the paths for scripts, too
138n/a self.distribution.scripts = [os.path.join(srcdir, filename)
139n/a for filename in self.distribution.scripts]
140n/a
141n/a # Python header files
142n/a headers = [sysconfig.get_config_h_filename()]
143n/a headers += glob(os.path.join(sysconfig.get_path('platinclude'), "*.h"))
144n/a for ext in self.extensions[:]:
145n/a ext.sources = [ find_module_file(filename, moddirlist)
146n/a for filename in ext.sources ]
147n/a if ext.depends is not None:
148n/a ext.depends = [find_module_file(filename, moddirlist)
149n/a for filename in ext.depends]
150n/a else:
151n/a ext.depends = []
152n/a # re-compile extensions if a header file has been changed
153n/a ext.depends.extend(headers)
154n/a
155n/a # platform specific include directories
156n/a ext.include_dirs.extend(incdirlist)
157n/a
158n/a # If a module has already been built statically,
159n/a # don't build it here
160n/a if ext.name in sys.builtin_module_names:
161n/a self.extensions.remove(ext)
162n/a
163n/a if platform != 'mac':
164n/a # Parse Modules/Setup and Modules/Setup.local to figure out which
165n/a # modules are turned on in the file.
166n/a remove_modules = []
167n/a for filename in ('Modules/Setup', 'Modules/Setup.local'):
168n/a input = text_file.TextFile(filename, join_lines=1)
169n/a while 1:
170n/a line = input.readline()
171n/a if not line: break
172n/a line = line.split()
173n/a remove_modules.append(line[0])
174n/a input.close()
175n/a
176n/a for ext in self.extensions[:]:
177n/a if ext.name in remove_modules:
178n/a self.extensions.remove(ext)
179n/a
180n/a # When you run "make CC=altcc" or something similar, you really want
181n/a # those environment variables passed into the setup.py phase. Here's
182n/a # a small set of useful ones.
183n/a compiler = os.environ.get('CC')
184n/a args = {}
185n/a # unfortunately, distutils doesn't let us provide separate C and C++
186n/a # compilers
187n/a if compiler is not None:
188n/a (ccshared,cflags) = sysconfig.get_config_vars('CCSHARED','CFLAGS')
189n/a args['compiler_so'] = compiler + ' ' + ccshared + ' ' + cflags
190n/a self.compiler.set_executables(**args)
191n/a
192n/a build_ext.build_extensions(self)
193n/a
194n/a longest = max([len(e.name) for e in self.extensions])
195n/a if self.failed:
196n/a longest = max(longest, max([len(name) for name in self.failed]))
197n/a
198n/a def print_three_column(lst):
199n/a lst.sort(key=str.lower)
200n/a # guarantee zip() doesn't drop anything
201n/a while len(lst) % 3:
202n/a lst.append("")
203n/a for e, f, g in zip(lst[::3], lst[1::3], lst[2::3]):
204n/a print "%-*s %-*s %-*s" % (longest, e, longest, f,
205n/a longest, g)
206n/a
207n/a if missing:
208n/a print
209n/a print ("Python build finished, but the necessary bits to build "
210n/a "these modules were not found:")
211n/a print_three_column(missing)
212n/a print ("To find the necessary bits, look in setup.py in"
213n/a " detect_modules() for the module's name.")
214n/a print
215n/a
216n/a if self.failed:
217n/a failed = self.failed[:]
218n/a print
219n/a print "Failed to build these modules:"
220n/a print_three_column(failed)
221n/a print
222n/a
223n/a def build_extension(self, ext):
224n/a
225n/a if ext.name == '_ctypes':
226n/a if not self.configure_ctypes(ext):
227n/a return
228n/a
229n/a try:
230n/a build_ext.build_extension(self, ext)
231n/a except (CCompilerError, DistutilsError), why:
232n/a self.announce('WARNING: building of extension "%s" failed: %s' %
233n/a (ext.name, sys.exc_info()[1]))
234n/a self.failed.append(ext.name)
235n/a return
236n/a # Workaround for Mac OS X: The Carbon-based modules cannot be
237n/a # reliably imported into a command-line Python
238n/a if 'Carbon' in ext.extra_link_args:
239n/a self.announce(
240n/a 'WARNING: skipping import check for Carbon-based "%s"' %
241n/a ext.name)
242n/a return
243n/a
244n/a if self.get_platform() == 'darwin' and (
245n/a sys.maxint > 2**32 and '-arch' in ext.extra_link_args):
246n/a # Don't bother doing an import check when an extension was
247n/a # build with an explicit '-arch' flag on OSX. That's currently
248n/a # only used to build 32-bit only extensions in a 4-way
249n/a # universal build and loading 32-bit code into a 64-bit
250n/a # process will fail.
251n/a self.announce(
252n/a 'WARNING: skipping import check for "%s"' %
253n/a ext.name)
254n/a return
255n/a
256n/a # Workaround for Cygwin: Cygwin currently has fork issues when many
257n/a # modules have been imported
258n/a if self.get_platform() == 'cygwin':
259n/a self.announce('WARNING: skipping import check for Cygwin-based "%s"'
260n/a % ext.name)
261n/a return
262n/a ext_filename = os.path.join(
263n/a self.build_lib,
264n/a self.get_ext_filename(self.get_ext_fullname(ext.name)))
265n/a try:
266n/a imp.load_dynamic(ext.name, ext_filename)
267n/a except ImportError, why:
268n/a self.failed.append(ext.name)
269n/a self.announce('*** WARNING: renaming "%s" since importing it'
270n/a ' failed: %s' % (ext.name, why), level=3)
271n/a assert not self.inplace
272n/a basename, tail = os.path.splitext(ext_filename)
273n/a newname = basename + "_failed" + tail
274n/a if os.path.exists(newname):
275n/a os.remove(newname)
276n/a os.rename(ext_filename, newname)
277n/a
278n/a # XXX -- This relies on a Vile HACK in
279n/a # distutils.command.build_ext.build_extension(). The
280n/a # _built_objects attribute is stored there strictly for
281n/a # use here.
282n/a # If there is a failure, _built_objects may not be there,
283n/a # so catch the AttributeError and move on.
284n/a try:
285n/a for filename in self._built_objects:
286n/a os.remove(filename)
287n/a except AttributeError:
288n/a self.announce('unable to remove files (ignored)')
289n/a except:
290n/a exc_type, why, tb = sys.exc_info()
291n/a self.announce('*** WARNING: importing extension "%s" '
292n/a 'failed with %s: %s' % (ext.name, exc_type, why),
293n/a level=3)
294n/a self.failed.append(ext.name)
295n/a
296n/a def get_platform(self):
297n/a # Get value of sys.platform
298n/a for platform in ['cygwin', 'beos', 'darwin', 'atheos', 'osf1']:
299n/a if sys.platform.startswith(platform):
300n/a return platform
301n/a return sys.platform
302n/a
303n/a def detect_modules(self):
304n/a # Ensure that /usr/local is always used
305n/a add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib')
306n/a add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
307n/a
308n/a # Add paths specified in the environment variables LDFLAGS and
309n/a # CPPFLAGS for header and library files.
310n/a # We must get the values from the Makefile and not the environment
311n/a # directly since an inconsistently reproducible issue comes up where
312n/a # the environment variable is not set even though the value were passed
313n/a # into configure and stored in the Makefile (issue found on OS X 10.3).
314n/a for env_var, arg_name, dir_list in (
315n/a ('LDFLAGS', '-R', self.compiler.runtime_library_dirs),
316n/a ('LDFLAGS', '-L', self.compiler.library_dirs),
317n/a ('CPPFLAGS', '-I', self.compiler.include_dirs)):
318n/a env_val = sysconfig.get_config_var(env_var)
319n/a if env_val:
320n/a # To prevent optparse from raising an exception about any
321n/a # options in env_val that it doesn't know about we strip out
322n/a # all double dashes and any dashes followed by a character
323n/a # that is not for the option we are dealing with.
324n/a #
325n/a # Please note that order of the regex is important! We must
326n/a # strip out double-dashes first so that we don't end up with
327n/a # substituting "--Long" to "-Long" and thus lead to "ong" being
328n/a # used for a library directory.
329n/a env_val = re.sub(r'(^|\s+)-(-|(?!%s))' % arg_name[1],
330n/a ' ', env_val)
331n/a parser = optparse.OptionParser()
332n/a # Make sure that allowing args interspersed with options is
333n/a # allowed
334n/a parser.allow_interspersed_args = True
335n/a parser.error = lambda msg: None
336n/a parser.add_option(arg_name, dest="dirs", action="append")
337n/a options = parser.parse_args(env_val.split())[0]
338n/a if options.dirs:
339n/a for directory in reversed(options.dirs):
340n/a add_dir_to_list(dir_list, directory)
341n/a
342n/a if os.path.normpath(sys.prefix) != '/usr':
343n/a add_dir_to_list(self.compiler.library_dirs,
344n/a sysconfig.get_config_var("LIBDIR"))
345n/a add_dir_to_list(self.compiler.include_dirs,
346n/a sysconfig.get_config_var("INCLUDEDIR"))
347n/a
348n/a try:
349n/a have_unicode = unicode
350n/a except NameError:
351n/a have_unicode = 0
352n/a
353n/a # lib_dirs and inc_dirs are used to search for files;
354n/a # if a file is found in one of those directories, it can
355n/a # be assumed that no additional -I,-L directives are needed.
356n/a lib_dirs = self.compiler.library_dirs + [
357n/a '/lib64', '/usr/lib64',
358n/a '/lib', '/usr/lib',
359n/a ]
360n/a inc_dirs = self.compiler.include_dirs + ['/usr/include']
361n/a exts = []
362n/a missing = []
363n/a
364n/a config_h = sysconfig.get_config_h_filename()
365n/a config_h_vars = sysconfig.parse_config_h(open(config_h))
366n/a
367n/a platform = self.get_platform()
368n/a srcdir = sysconfig.get_config_var('srcdir')
369n/a
370n/a # Check for AtheOS which has libraries in non-standard locations
371n/a if platform == 'atheos':
372n/a lib_dirs += ['/system/libs', '/atheos/autolnk/lib']
373n/a lib_dirs += os.getenv('LIBRARY_PATH', '').split(os.pathsep)
374n/a inc_dirs += ['/system/include', '/atheos/autolnk/include']
375n/a inc_dirs += os.getenv('C_INCLUDE_PATH', '').split(os.pathsep)
376n/a
377n/a # OSF/1 and Unixware have some stuff in /usr/ccs/lib (like -ldb)
378n/a if platform in ['osf1', 'unixware7', 'openunix8']:
379n/a lib_dirs += ['/usr/ccs/lib']
380n/a
381n/a if platform == 'darwin':
382n/a # This should work on any unixy platform ;-)
383n/a # If the user has bothered specifying additional -I and -L flags
384n/a # in OPT and LDFLAGS we might as well use them here.
385n/a # NOTE: using shlex.split would technically be more correct, but
386n/a # also gives a bootstrap problem. Let's hope nobody uses directories
387n/a # with whitespace in the name to store libraries.
388n/a cflags, ldflags = sysconfig.get_config_vars(
389n/a 'CFLAGS', 'LDFLAGS')
390n/a for item in cflags.split():
391n/a if item.startswith('-I'):
392n/a inc_dirs.append(item[2:])
393n/a
394n/a for item in ldflags.split():
395n/a if item.startswith('-L'):
396n/a lib_dirs.append(item[2:])
397n/a
398n/a # Check for MacOS X, which doesn't need libm.a at all
399n/a math_libs = ['m']
400n/a if platform in ['darwin', 'beos', 'mac']:
401n/a math_libs = []
402n/a
403n/a # XXX Omitted modules: gl, pure, dl, SGI-specific modules
404n/a
405n/a #
406n/a # The following modules are all pretty straightforward, and compile
407n/a # on pretty much any POSIXish platform.
408n/a #
409n/a
410n/a # Some modules that are normally always on:
411n/a exts.append( Extension('_weakref', ['_weakref.c']) )
412n/a
413n/a # array objects
414n/a exts.append( Extension('array', ['arraymodule.c']) )
415n/a # complex math library functions
416n/a exts.append( Extension('cmath', ['cmathmodule.c', '_math.c'],
417n/a depends=['_math.h'],
418n/a libraries=math_libs) )
419n/a # math library functions, e.g. sin()
420n/a exts.append( Extension('math', ['mathmodule.c', '_math.c'],
421n/a depends=['_math.h'],
422n/a libraries=math_libs) )
423n/a # fast string operations implemented in C
424n/a exts.append( Extension('strop', ['stropmodule.c']) )
425n/a # time operations and variables
426n/a exts.append( Extension('time', ['timemodule.c'],
427n/a libraries=math_libs) )
428n/a exts.append( Extension('datetime', ['datetimemodule.c', 'timemodule.c'],
429n/a libraries=math_libs) )
430n/a # fast iterator tools implemented in C
431n/a exts.append( Extension("itertools", ["itertoolsmodule.c"]) )
432n/a # code that will be builtins in the future, but conflict with the
433n/a # current builtins
434n/a exts.append( Extension('future_builtins', ['future_builtins.c']) )
435n/a # random number generator implemented in C
436n/a exts.append( Extension("_random", ["_randommodule.c"]) )
437n/a # high-performance collections
438n/a exts.append( Extension("_collections", ["_collectionsmodule.c"]) )
439n/a # bisect
440n/a exts.append( Extension("_bisect", ["_bisectmodule.c"]) )
441n/a # heapq
442n/a exts.append( Extension("_heapq", ["_heapqmodule.c"]) )
443n/a # operator.add() and similar goodies
444n/a exts.append( Extension('operator', ['operator.c']) )
445n/a # Python 3.1 _io library
446n/a exts.append( Extension("_io",
447n/a ["_io/bufferedio.c", "_io/bytesio.c", "_io/fileio.c",
448n/a "_io/iobase.c", "_io/_iomodule.c", "_io/stringio.c", "_io/textio.c"],
449n/a depends=["_io/_iomodule.h"], include_dirs=["Modules/_io"]))
450n/a # _functools
451n/a exts.append( Extension("_functools", ["_functoolsmodule.c"]) )
452n/a # _json speedups
453n/a exts.append( Extension("_json", ["_json.c"]) )
454n/a # Python C API test module
455n/a exts.append( Extension('_testcapi', ['_testcapimodule.c'],
456n/a depends=['testcapi_long.h']) )
457n/a # profilers (_lsprof is for cProfile.py)
458n/a exts.append( Extension('_hotshot', ['_hotshot.c']) )
459n/a exts.append( Extension('_lsprof', ['_lsprof.c', 'rotatingtree.c']) )
460n/a # static Unicode character database
461n/a if have_unicode:
462n/a exts.append( Extension('unicodedata', ['unicodedata.c']) )
463n/a else:
464n/a missing.append('unicodedata')
465n/a # access to ISO C locale support
466n/a data = open('pyconfig.h').read()
467n/a m = re.search(r"#s*define\s+WITH_LIBINTL\s+1\s*", data)
468n/a if m is not None:
469n/a locale_libs = ['intl']
470n/a else:
471n/a locale_libs = []
472n/a if platform == 'darwin':
473n/a locale_extra_link_args = ['-framework', 'CoreFoundation']
474n/a else:
475n/a locale_extra_link_args = []
476n/a
477n/a
478n/a exts.append( Extension('_locale', ['_localemodule.c'],
479n/a libraries=locale_libs,
480n/a extra_link_args=locale_extra_link_args) )
481n/a
482n/a # Modules with some UNIX dependencies -- on by default:
483n/a # (If you have a really backward UNIX, select and socket may not be
484n/a # supported...)
485n/a
486n/a # fcntl(2) and ioctl(2)
487n/a exts.append( Extension('fcntl', ['fcntlmodule.c']) )
488n/a if platform not in ['mac']:
489n/a # pwd(3)
490n/a exts.append( Extension('pwd', ['pwdmodule.c']) )
491n/a # grp(3)
492n/a exts.append( Extension('grp', ['grpmodule.c']) )
493n/a # spwd, shadow passwords
494n/a if (config_h_vars.get('HAVE_GETSPNAM', False) or
495n/a config_h_vars.get('HAVE_GETSPENT', False)):
496n/a exts.append( Extension('spwd', ['spwdmodule.c']) )
497n/a else:
498n/a missing.append('spwd')
499n/a else:
500n/a missing.extend(['pwd', 'grp', 'spwd'])
501n/a
502n/a # select(2); not on ancient System V
503n/a exts.append( Extension('select', ['selectmodule.c']) )
504n/a
505n/a # Fred Drake's interface to the Python parser
506n/a exts.append( Extension('parser', ['parsermodule.c']) )
507n/a
508n/a # cStringIO and cPickle
509n/a exts.append( Extension('cStringIO', ['cStringIO.c']) )
510n/a exts.append( Extension('cPickle', ['cPickle.c']) )
511n/a
512n/a # Memory-mapped files (also works on Win32).
513n/a if platform not in ['atheos', 'mac']:
514n/a exts.append( Extension('mmap', ['mmapmodule.c']) )
515n/a else:
516n/a missing.append('mmap')
517n/a
518n/a # Lance Ellinghaus's syslog module
519n/a if platform not in ['mac']:
520n/a # syslog daemon interface
521n/a exts.append( Extension('syslog', ['syslogmodule.c']) )
522n/a else:
523n/a missing.append('syslog')
524n/a
525n/a # George Neville-Neil's timing module:
526n/a # Deprecated in PEP 4 http://www.python.org/peps/pep-0004.html
527n/a # http://mail.python.org/pipermail/python-dev/2006-January/060023.html
528n/a #exts.append( Extension('timing', ['timingmodule.c']) )
529n/a
530n/a #
531n/a # Here ends the simple stuff. From here on, modules need certain
532n/a # libraries, are platform-specific, or present other surprises.
533n/a #
534n/a
535n/a # Multimedia modules
536n/a # These don't work for 64-bit platforms!!!
537n/a # These represent audio samples or images as strings:
538n/a
539n/a # Operations on audio samples
540n/a # According to #993173, this one should actually work fine on
541n/a # 64-bit platforms.
542n/a exts.append( Extension('audioop', ['audioop.c']) )
543n/a
544n/a # Disabled on 64-bit platforms
545n/a if sys.maxint != 9223372036854775807L:
546n/a # Operations on images
547n/a exts.append( Extension('imageop', ['imageop.c']) )
548n/a else:
549n/a missing.extend(['imageop'])
550n/a
551n/a # readline
552n/a do_readline = self.compiler.find_library_file(lib_dirs, 'readline')
553n/a if platform == 'darwin':
554n/a os_release = int(os.uname()[2].split('.')[0])
555n/a dep_target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
556n/a if dep_target and dep_target.split('.') < ['10', '5']:
557n/a os_release = 8
558n/a if os_release < 9:
559n/a # MacOSX 10.4 has a broken readline. Don't try to build
560n/a # the readline module unless the user has installed a fixed
561n/a # readline package
562n/a if find_file('readline/rlconf.h', inc_dirs, []) is None:
563n/a do_readline = False
564n/a if do_readline:
565n/a if platform == 'darwin' and os_release < 9:
566n/a # In every directory on the search path search for a dynamic
567n/a # library and then a static library, instead of first looking
568n/a # for dynamic libraries on the entiry path.
569n/a # This way a staticly linked custom readline gets picked up
570n/a # before the (broken) dynamic library in /usr/lib.
571n/a readline_extra_link_args = ('-Wl,-search_paths_first',)
572n/a else:
573n/a readline_extra_link_args = ()
574n/a
575n/a readline_libs = ['readline']
576n/a if self.compiler.find_library_file(lib_dirs,
577n/a 'ncursesw'):
578n/a readline_libs.append('ncursesw')
579n/a elif self.compiler.find_library_file(lib_dirs,
580n/a 'ncurses'):
581n/a readline_libs.append('ncurses')
582n/a elif self.compiler.find_library_file(lib_dirs, 'curses'):
583n/a readline_libs.append('curses')
584n/a elif self.compiler.find_library_file(lib_dirs +
585n/a ['/usr/lib/termcap'],
586n/a 'termcap'):
587n/a readline_libs.append('termcap')
588n/a exts.append( Extension('readline', ['readline.c'],
589n/a library_dirs=['/usr/lib/termcap'],
590n/a extra_link_args=readline_extra_link_args,
591n/a libraries=readline_libs) )
592n/a else:
593n/a missing.append('readline')
594n/a
595n/a if platform not in ['mac']:
596n/a # crypt module.
597n/a
598n/a if self.compiler.find_library_file(lib_dirs, 'crypt'):
599n/a libs = ['crypt']
600n/a else:
601n/a libs = []
602n/a exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) )
603n/a else:
604n/a missing.append('crypt')
605n/a
606n/a # CSV files
607n/a exts.append( Extension('_csv', ['_csv.c']) )
608n/a
609n/a # socket(2)
610n/a exts.append( Extension('_socket', ['socketmodule.c'],
611n/a depends = ['socketmodule.h']) )
612n/a # Detect SSL support for the socket module (via _ssl)
613n/a search_for_ssl_incs_in = [
614n/a '/usr/local/ssl/include',
615n/a '/usr/contrib/ssl/include/'
616n/a ]
617n/a ssl_incs = find_file('openssl/ssl.h', inc_dirs,
618n/a search_for_ssl_incs_in
619n/a )
620n/a if ssl_incs is not None:
621n/a krb5_h = find_file('krb5.h', inc_dirs,
622n/a ['/usr/kerberos/include'])
623n/a if krb5_h:
624n/a ssl_incs += krb5_h
625n/a ssl_libs = find_library_file(self.compiler, 'ssl',lib_dirs,
626n/a ['/usr/local/ssl/lib',
627n/a '/usr/contrib/ssl/lib/'
628n/a ] )
629n/a
630n/a if (ssl_incs is not None and
631n/a ssl_libs is not None):
632n/a exts.append( Extension('_ssl', ['_ssl.c'],
633n/a include_dirs = ssl_incs,
634n/a library_dirs = ssl_libs,
635n/a libraries = ['ssl', 'crypto'],
636n/a depends = ['socketmodule.h']), )
637n/a else:
638n/a missing.append('_ssl')
639n/a
640n/a # find out which version of OpenSSL we have
641n/a openssl_ver = 0
642n/a openssl_ver_re = re.compile(
643n/a '^\s*#\s*define\s+OPENSSL_VERSION_NUMBER\s+(0x[0-9a-fA-F]+)' )
644n/a for ssl_inc_dir in inc_dirs + search_for_ssl_incs_in:
645n/a name = os.path.join(ssl_inc_dir, 'openssl', 'opensslv.h')
646n/a if os.path.isfile(name):
647n/a try:
648n/a incfile = open(name, 'r')
649n/a for line in incfile:
650n/a m = openssl_ver_re.match(line)
651n/a if m:
652n/a openssl_ver = eval(m.group(1))
653n/a break
654n/a except IOError:
655n/a pass
656n/a
657n/a # first version found is what we'll use (as the compiler should)
658n/a if openssl_ver:
659n/a break
660n/a
661n/a #print 'openssl_ver = 0x%08x' % openssl_ver
662n/a min_openssl_ver = 0x00907000
663n/a have_any_openssl = ssl_incs is not None and ssl_libs is not None
664n/a have_usable_openssl = (have_any_openssl and
665n/a openssl_ver >= min_openssl_ver)
666n/a
667n/a if have_any_openssl:
668n/a if have_usable_openssl:
669n/a # The _hashlib module wraps optimized implementations
670n/a # of hash functions from the OpenSSL library.
671n/a exts.append( Extension('_hashlib', ['_hashopenssl.c'],
672n/a include_dirs = ssl_incs,
673n/a library_dirs = ssl_libs,
674n/a libraries = ['ssl', 'crypto']) )
675n/a else:
676n/a print ("warning: openssl 0x%08x is too old for _hashlib" %
677n/a openssl_ver)
678n/a missing.append('_hashlib')
679n/a if COMPILED_WITH_PYDEBUG or not have_usable_openssl:
680n/a # The _sha module implements the SHA1 hash algorithm.
681n/a exts.append( Extension('_sha', ['shamodule.c']) )
682n/a # The _md5 module implements the RSA Data Security, Inc. MD5
683n/a # Message-Digest Algorithm, described in RFC 1321. The
684n/a # necessary files md5.c and md5.h are included here.
685n/a exts.append( Extension('_md5',
686n/a sources = ['md5module.c', 'md5.c'],
687n/a depends = ['md5.h']) )
688n/a
689n/a min_sha2_openssl_ver = 0x00908000
690n/a if COMPILED_WITH_PYDEBUG or openssl_ver < min_sha2_openssl_ver:
691n/a # OpenSSL doesn't do these until 0.9.8 so we'll bring our own hash
692n/a exts.append( Extension('_sha256', ['sha256module.c']) )
693n/a exts.append( Extension('_sha512', ['sha512module.c']) )
694n/a
695n/a # Modules that provide persistent dictionary-like semantics. You will
696n/a # probably want to arrange for at least one of them to be available on
697n/a # your machine, though none are defined by default because of library
698n/a # dependencies. The Python module anydbm.py provides an
699n/a # implementation independent wrapper for these; dumbdbm.py provides
700n/a # similar functionality (but slower of course) implemented in Python.
701n/a
702n/a # Sleepycat^WOracle Berkeley DB interface.
703n/a # http://www.oracle.com/database/berkeley-db/db/index.html
704n/a #
705n/a # This requires the Sleepycat^WOracle DB code. The supported versions
706n/a # are set below. Visit the URL above to download
707n/a # a release. Most open source OSes come with one or more
708n/a # versions of BerkeleyDB already installed.
709n/a
710n/a max_db_ver = (4, 7)
711n/a min_db_ver = (3, 3)
712n/a db_setup_debug = False # verbose debug prints from this script?
713n/a
714n/a def allow_db_ver(db_ver):
715n/a """Returns a boolean if the given BerkeleyDB version is acceptable.
716n/a
717n/a Args:
718n/a db_ver: A tuple of the version to verify.
719n/a """
720n/a if not (min_db_ver <= db_ver <= max_db_ver):
721n/a return False
722n/a # Use this function to filter out known bad configurations.
723n/a if (4, 6) == db_ver[:2]:
724n/a # BerkeleyDB 4.6.x is not stable on many architectures.
725n/a arch = platform_machine()
726n/a if arch not in ('i386', 'i486', 'i586', 'i686',
727n/a 'x86_64', 'ia64'):
728n/a return False
729n/a return True
730n/a
731n/a def gen_db_minor_ver_nums(major):
732n/a if major == 4:
733n/a for x in range(max_db_ver[1]+1):
734n/a if allow_db_ver((4, x)):
735n/a yield x
736n/a elif major == 3:
737n/a for x in (3,):
738n/a if allow_db_ver((3, x)):
739n/a yield x
740n/a else:
741n/a raise ValueError("unknown major BerkeleyDB version", major)
742n/a
743n/a # construct a list of paths to look for the header file in on
744n/a # top of the normal inc_dirs.
745n/a db_inc_paths = [
746n/a '/usr/include/db4',
747n/a '/usr/local/include/db4',
748n/a '/opt/sfw/include/db4',
749n/a '/usr/include/db3',
750n/a '/usr/local/include/db3',
751n/a '/opt/sfw/include/db3',
752n/a # Fink defaults (http://fink.sourceforge.net/)
753n/a '/sw/include/db4',
754n/a '/sw/include/db3',
755n/a ]
756n/a # 4.x minor number specific paths
757n/a for x in gen_db_minor_ver_nums(4):
758n/a db_inc_paths.append('/usr/include/db4%d' % x)
759n/a db_inc_paths.append('/usr/include/db4.%d' % x)
760n/a db_inc_paths.append('/usr/local/BerkeleyDB.4.%d/include' % x)
761n/a db_inc_paths.append('/usr/local/include/db4%d' % x)
762n/a db_inc_paths.append('/pkg/db-4.%d/include' % x)
763n/a db_inc_paths.append('/opt/db-4.%d/include' % x)
764n/a # MacPorts default (http://www.macports.org/)
765n/a db_inc_paths.append('/opt/local/include/db4%d' % x)
766n/a # 3.x minor number specific paths
767n/a for x in gen_db_minor_ver_nums(3):
768n/a db_inc_paths.append('/usr/include/db3%d' % x)
769n/a db_inc_paths.append('/usr/local/BerkeleyDB.3.%d/include' % x)
770n/a db_inc_paths.append('/usr/local/include/db3%d' % x)
771n/a db_inc_paths.append('/pkg/db-3.%d/include' % x)
772n/a db_inc_paths.append('/opt/db-3.%d/include' % x)
773n/a
774n/a # Add some common subdirectories for Sleepycat DB to the list,
775n/a # based on the standard include directories. This way DB3/4 gets
776n/a # picked up when it is installed in a non-standard prefix and
777n/a # the user has added that prefix into inc_dirs.
778n/a std_variants = []
779n/a for dn in inc_dirs:
780n/a std_variants.append(os.path.join(dn, 'db3'))
781n/a std_variants.append(os.path.join(dn, 'db4'))
782n/a for x in gen_db_minor_ver_nums(4):
783n/a std_variants.append(os.path.join(dn, "db4%d"%x))
784n/a std_variants.append(os.path.join(dn, "db4.%d"%x))
785n/a for x in gen_db_minor_ver_nums(3):
786n/a std_variants.append(os.path.join(dn, "db3%d"%x))
787n/a std_variants.append(os.path.join(dn, "db3.%d"%x))
788n/a
789n/a db_inc_paths = std_variants + db_inc_paths
790n/a db_inc_paths = [p for p in db_inc_paths if os.path.exists(p)]
791n/a
792n/a db_ver_inc_map = {}
793n/a
794n/a class db_found(Exception): pass
795n/a try:
796n/a # See whether there is a Sleepycat header in the standard
797n/a # search path.
798n/a for d in inc_dirs + db_inc_paths:
799n/a f = os.path.join(d, "db.h")
800n/a if db_setup_debug: print "db: looking for db.h in", f
801n/a if os.path.exists(f):
802n/a f = open(f).read()
803n/a m = re.search(r"#define\WDB_VERSION_MAJOR\W(\d+)", f)
804n/a if m:
805n/a db_major = int(m.group(1))
806n/a m = re.search(r"#define\WDB_VERSION_MINOR\W(\d+)", f)
807n/a db_minor = int(m.group(1))
808n/a db_ver = (db_major, db_minor)
809n/a
810n/a # Avoid 4.6 prior to 4.6.21 due to a BerkeleyDB bug
811n/a if db_ver == (4, 6):
812n/a m = re.search(r"#define\WDB_VERSION_PATCH\W(\d+)", f)
813n/a db_patch = int(m.group(1))
814n/a if db_patch < 21:
815n/a print "db.h:", db_ver, "patch", db_patch,
816n/a print "being ignored (4.6.x must be >= 4.6.21)"
817n/a continue
818n/a
819n/a if ( (db_ver not in db_ver_inc_map) and
820n/a allow_db_ver(db_ver) ):
821n/a # save the include directory with the db.h version
822n/a # (first occurrence only)
823n/a db_ver_inc_map[db_ver] = d
824n/a if db_setup_debug:
825n/a print "db.h: found", db_ver, "in", d
826n/a else:
827n/a # we already found a header for this library version
828n/a if db_setup_debug: print "db.h: ignoring", d
829n/a else:
830n/a # ignore this header, it didn't contain a version number
831n/a if db_setup_debug:
832n/a print "db.h: no version number version in", d
833n/a
834n/a db_found_vers = db_ver_inc_map.keys()
835n/a db_found_vers.sort()
836n/a
837n/a while db_found_vers:
838n/a db_ver = db_found_vers.pop()
839n/a db_incdir = db_ver_inc_map[db_ver]
840n/a
841n/a # check lib directories parallel to the location of the header
842n/a db_dirs_to_check = [
843n/a db_incdir.replace("include", 'lib64'),
844n/a db_incdir.replace("include", 'lib'),
845n/a ]
846n/a db_dirs_to_check = filter(os.path.isdir, db_dirs_to_check)
847n/a
848n/a # Look for a version specific db-X.Y before an ambiguoius dbX
849n/a # XXX should we -ever- look for a dbX name? Do any
850n/a # systems really not name their library by version and
851n/a # symlink to more general names?
852n/a for dblib in (('db-%d.%d' % db_ver),
853n/a ('db%d%d' % db_ver),
854n/a ('db%d' % db_ver[0])):
855n/a dblib_file = self.compiler.find_library_file(
856n/a db_dirs_to_check + lib_dirs, dblib )
857n/a if dblib_file:
858n/a dblib_dir = [ os.path.abspath(os.path.dirname(dblib_file)) ]
859n/a raise db_found
860n/a else:
861n/a if db_setup_debug: print "db lib: ", dblib, "not found"
862n/a
863n/a except db_found:
864n/a if db_setup_debug:
865n/a print "bsddb using BerkeleyDB lib:", db_ver, dblib
866n/a print "bsddb lib dir:", dblib_dir, " inc dir:", db_incdir
867n/a db_incs = [db_incdir]
868n/a dblibs = [dblib]
869n/a # We add the runtime_library_dirs argument because the
870n/a # BerkeleyDB lib we're linking against often isn't in the
871n/a # system dynamic library search path. This is usually
872n/a # correct and most trouble free, but may cause problems in
873n/a # some unusual system configurations (e.g. the directory
874n/a # is on an NFS server that goes away).
875n/a exts.append(Extension('_bsddb', ['_bsddb.c'],
876n/a depends = ['bsddb.h'],
877n/a library_dirs=dblib_dir,
878n/a runtime_library_dirs=dblib_dir,
879n/a include_dirs=db_incs,
880n/a libraries=dblibs))
881n/a else:
882n/a if db_setup_debug: print "db: no appropriate library found"
883n/a db_incs = None
884n/a dblibs = []
885n/a dblib_dir = None
886n/a missing.append('_bsddb')
887n/a
888n/a # The sqlite interface
889n/a sqlite_setup_debug = False # verbose debug prints from this script?
890n/a
891n/a # We hunt for #define SQLITE_VERSION "n.n.n"
892n/a # We need to find >= sqlite version 3.0.8
893n/a sqlite_incdir = sqlite_libdir = None
894n/a sqlite_inc_paths = [ '/usr/include',
895n/a '/usr/include/sqlite',
896n/a '/usr/include/sqlite3',
897n/a '/usr/local/include',
898n/a '/usr/local/include/sqlite',
899n/a '/usr/local/include/sqlite3',
900n/a ]
901n/a MIN_SQLITE_VERSION_NUMBER = (3, 0, 8)
902n/a MIN_SQLITE_VERSION = ".".join([str(x)
903n/a for x in MIN_SQLITE_VERSION_NUMBER])
904n/a
905n/a # Scan the default include directories before the SQLite specific
906n/a # ones. This allows one to override the copy of sqlite on OSX,
907n/a # where /usr/include contains an old version of sqlite.
908n/a for d in inc_dirs + sqlite_inc_paths:
909n/a f = os.path.join(d, "sqlite3.h")
910n/a if os.path.exists(f):
911n/a if sqlite_setup_debug: print "sqlite: found %s"%f
912n/a incf = open(f).read()
913n/a m = re.search(
914n/a r'\s*.*#\s*.*define\s.*SQLITE_VERSION\W*"(.*)"', incf)
915n/a if m:
916n/a sqlite_version = m.group(1)
917n/a sqlite_version_tuple = tuple([int(x)
918n/a for x in sqlite_version.split(".")])
919n/a if sqlite_version_tuple >= MIN_SQLITE_VERSION_NUMBER:
920n/a # we win!
921n/a if sqlite_setup_debug:
922n/a print "%s/sqlite3.h: version %s"%(d, sqlite_version)
923n/a sqlite_incdir = d
924n/a break
925n/a else:
926n/a if sqlite_setup_debug:
927n/a print "%s: version %d is too old, need >= %s"%(d,
928n/a sqlite_version, MIN_SQLITE_VERSION)
929n/a elif sqlite_setup_debug:
930n/a print "sqlite: %s had no SQLITE_VERSION"%(f,)
931n/a
932n/a if sqlite_incdir:
933n/a sqlite_dirs_to_check = [
934n/a os.path.join(sqlite_incdir, '..', 'lib64'),
935n/a os.path.join(sqlite_incdir, '..', 'lib'),
936n/a os.path.join(sqlite_incdir, '..', '..', 'lib64'),
937n/a os.path.join(sqlite_incdir, '..', '..', 'lib'),
938n/a ]
939n/a sqlite_libfile = self.compiler.find_library_file(
940n/a sqlite_dirs_to_check + lib_dirs, 'sqlite3')
941n/a if sqlite_libfile:
942n/a sqlite_libdir = [os.path.abspath(os.path.dirname(sqlite_libfile))]
943n/a
944n/a if sqlite_incdir and sqlite_libdir:
945n/a sqlite_srcs = ['_sqlite/cache.c',
946n/a '_sqlite/connection.c',
947n/a '_sqlite/cursor.c',
948n/a '_sqlite/microprotocols.c',
949n/a '_sqlite/module.c',
950n/a '_sqlite/prepare_protocol.c',
951n/a '_sqlite/row.c',
952n/a '_sqlite/statement.c',
953n/a '_sqlite/util.c', ]
954n/a
955n/a sqlite_defines = []
956n/a if sys.platform != "win32":
957n/a sqlite_defines.append(('MODULE_NAME', '"sqlite3"'))
958n/a else:
959n/a sqlite_defines.append(('MODULE_NAME', '\\"sqlite3\\"'))
960n/a
961n/a # Comment this out if you want the sqlite3 module to be able to load extensions.
962n/a sqlite_defines.append(("SQLITE_OMIT_LOAD_EXTENSION", "1"))
963n/a
964n/a if sys.platform == 'darwin':
965n/a # In every directory on the search path search for a dynamic
966n/a # library and then a static library, instead of first looking
967n/a # for dynamic libraries on the entiry path.
968n/a # This way a staticly linked custom sqlite gets picked up
969n/a # before the dynamic library in /usr/lib.
970n/a sqlite_extra_link_args = ('-Wl,-search_paths_first',)
971n/a else:
972n/a sqlite_extra_link_args = ()
973n/a
974n/a exts.append(Extension('_sqlite3', sqlite_srcs,
975n/a define_macros=sqlite_defines,
976n/a include_dirs=["Modules/_sqlite",
977n/a sqlite_incdir],
978n/a library_dirs=sqlite_libdir,
979n/a runtime_library_dirs=sqlite_libdir,
980n/a extra_link_args=sqlite_extra_link_args,
981n/a libraries=["sqlite3",]))
982n/a else:
983n/a missing.append('_sqlite3')
984n/a
985n/a # Look for Berkeley db 1.85. Note that it is built as a different
986n/a # module name so it can be included even when later versions are
987n/a # available. A very restrictive search is performed to avoid
988n/a # accidentally building this module with a later version of the
989n/a # underlying db library. May BSD-ish Unixes incorporate db 1.85
990n/a # symbols into libc and place the include file in /usr/include.
991n/a #
992n/a # If the better bsddb library can be built (db_incs is defined)
993n/a # we do not build this one. Otherwise this build will pick up
994n/a # the more recent berkeleydb's db.h file first in the include path
995n/a # when attempting to compile and it will fail.
996n/a f = "/usr/include/db.h"
997n/a if os.path.exists(f) and not db_incs:
998n/a data = open(f).read()
999n/a m = re.search(r"#s*define\s+HASHVERSION\s+2\s*", data)
1000n/a if m is not None:
1001n/a # bingo - old version used hash file format version 2
1002n/a ### XXX this should be fixed to not be platform-dependent
1003n/a ### but I don't have direct access to an osf1 platform and
1004n/a ### seemed to be muffing the search somehow
1005n/a libraries = platform == "osf1" and ['db'] or None
1006n/a if libraries is not None:
1007n/a exts.append(Extension('bsddb185', ['bsddbmodule.c'],
1008n/a libraries=libraries))
1009n/a else:
1010n/a exts.append(Extension('bsddb185', ['bsddbmodule.c']))
1011n/a else:
1012n/a missing.append('bsddb185')
1013n/a else:
1014n/a missing.append('bsddb185')
1015n/a
1016n/a dbm_order = ['gdbm']
1017n/a # The standard Unix dbm module:
1018n/a if platform not in ['cygwin']:
1019n/a config_args = [arg.strip("'")
1020n/a for arg in sysconfig.get_config_var("CONFIG_ARGS").split()]
1021n/a dbm_args = [arg for arg in config_args
1022n/a if arg.startswith('--with-dbmliborder=')]
1023n/a if dbm_args:
1024n/a dbm_order = [arg.split('=')[-1] for arg in dbm_args][-1].split(":")
1025n/a else:
1026n/a dbm_order = "ndbm:gdbm:bdb".split(":")
1027n/a dbmext = None
1028n/a for cand in dbm_order:
1029n/a if cand == "ndbm":
1030n/a if find_file("ndbm.h", inc_dirs, []) is not None:
1031n/a # Some systems have -lndbm, others don't
1032n/a if self.compiler.find_library_file(lib_dirs,
1033n/a 'ndbm'):
1034n/a ndbm_libs = ['ndbm']
1035n/a else:
1036n/a ndbm_libs = []
1037n/a print "building dbm using ndbm"
1038n/a dbmext = Extension('dbm', ['dbmmodule.c'],
1039n/a define_macros=[
1040n/a ('HAVE_NDBM_H',None),
1041n/a ],
1042n/a libraries=ndbm_libs)
1043n/a break
1044n/a
1045n/a elif cand == "gdbm":
1046n/a if self.compiler.find_library_file(lib_dirs, 'gdbm'):
1047n/a gdbm_libs = ['gdbm']
1048n/a if self.compiler.find_library_file(lib_dirs,
1049n/a 'gdbm_compat'):
1050n/a gdbm_libs.append('gdbm_compat')
1051n/a if find_file("gdbm/ndbm.h", inc_dirs, []) is not None:
1052n/a print "building dbm using gdbm"
1053n/a dbmext = Extension(
1054n/a 'dbm', ['dbmmodule.c'],
1055n/a define_macros=[
1056n/a ('HAVE_GDBM_NDBM_H', None),
1057n/a ],
1058n/a libraries = gdbm_libs)
1059n/a break
1060n/a if find_file("gdbm-ndbm.h", inc_dirs, []) is not None:
1061n/a print "building dbm using gdbm"
1062n/a dbmext = Extension(
1063n/a 'dbm', ['dbmmodule.c'],
1064n/a define_macros=[
1065n/a ('HAVE_GDBM_DASH_NDBM_H', None),
1066n/a ],
1067n/a libraries = gdbm_libs)
1068n/a break
1069n/a elif cand == "bdb":
1070n/a if db_incs is not None:
1071n/a print "building dbm using bdb"
1072n/a dbmext = Extension('dbm', ['dbmmodule.c'],
1073n/a library_dirs=dblib_dir,
1074n/a runtime_library_dirs=dblib_dir,
1075n/a include_dirs=db_incs,
1076n/a define_macros=[
1077n/a ('HAVE_BERKDB_H', None),
1078n/a ('DB_DBM_HSEARCH', None),
1079n/a ],
1080n/a libraries=dblibs)
1081n/a break
1082n/a if dbmext is not None:
1083n/a exts.append(dbmext)
1084n/a else:
1085n/a missing.append('dbm')
1086n/a
1087n/a # Anthony Baxter's gdbm module. GNU dbm(3) will require -lgdbm:
1088n/a if ('gdbm' in dbm_order and
1089n/a self.compiler.find_library_file(lib_dirs, 'gdbm')):
1090n/a exts.append( Extension('gdbm', ['gdbmmodule.c'],
1091n/a libraries = ['gdbm'] ) )
1092n/a else:
1093n/a missing.append('gdbm')
1094n/a
1095n/a # Unix-only modules
1096n/a if platform not in ['mac', 'win32']:
1097n/a # Steen Lumholt's termios module
1098n/a exts.append( Extension('termios', ['termios.c']) )
1099n/a # Jeremy Hylton's rlimit interface
1100n/a if platform not in ['atheos']:
1101n/a exts.append( Extension('resource', ['resource.c']) )
1102n/a else:
1103n/a missing.append('resource')
1104n/a
1105n/a # Sun yellow pages. Some systems have the functions in libc.
1106n/a if (platform not in ['cygwin', 'atheos', 'qnx6'] and
1107n/a find_file('rpcsvc/yp_prot.h', inc_dirs, []) is not None):
1108n/a if (self.compiler.find_library_file(lib_dirs, 'nsl')):
1109n/a libs = ['nsl']
1110n/a else:
1111n/a libs = []
1112n/a exts.append( Extension('nis', ['nismodule.c'],
1113n/a libraries = libs) )
1114n/a else:
1115n/a missing.append('nis')
1116n/a else:
1117n/a missing.extend(['nis', 'resource', 'termios'])
1118n/a
1119n/a # Curses support, requiring the System V version of curses, often
1120n/a # provided by the ncurses library.
1121n/a panel_library = 'panel'
1122n/a if (self.compiler.find_library_file(lib_dirs, 'ncursesw')):
1123n/a curses_libs = ['ncursesw']
1124n/a # Bug 1464056: If _curses.so links with ncursesw,
1125n/a # _curses_panel.so must link with panelw.
1126n/a panel_library = 'panelw'
1127n/a exts.append( Extension('_curses', ['_cursesmodule.c'],
1128n/a libraries = curses_libs) )
1129n/a elif (self.compiler.find_library_file(lib_dirs, 'ncurses')):
1130n/a curses_libs = ['ncurses']
1131n/a exts.append( Extension('_curses', ['_cursesmodule.c'],
1132n/a libraries = curses_libs) )
1133n/a elif (self.compiler.find_library_file(lib_dirs, 'curses')
1134n/a and platform != 'darwin'):
1135n/a # OSX has an old Berkeley curses, not good enough for
1136n/a # the _curses module.
1137n/a if (self.compiler.find_library_file(lib_dirs, 'terminfo')):
1138n/a curses_libs = ['curses', 'terminfo']
1139n/a elif (self.compiler.find_library_file(lib_dirs, 'termcap')):
1140n/a curses_libs = ['curses', 'termcap']
1141n/a else:
1142n/a curses_libs = ['curses']
1143n/a
1144n/a exts.append( Extension('_curses', ['_cursesmodule.c'],
1145n/a libraries = curses_libs) )
1146n/a else:
1147n/a missing.append('_curses')
1148n/a
1149n/a # If the curses module is enabled, check for the panel module
1150n/a if (module_enabled(exts, '_curses') and
1151n/a self.compiler.find_library_file(lib_dirs, panel_library)):
1152n/a exts.append( Extension('_curses_panel', ['_curses_panel.c'],
1153n/a libraries = [panel_library] + curses_libs) )
1154n/a else:
1155n/a missing.append('_curses_panel')
1156n/a
1157n/a # Andrew Kuchling's zlib module. Note that some versions of zlib
1158n/a # 1.1.3 have security problems. See CERT Advisory CA-2002-07:
1159n/a # http://www.cert.org/advisories/CA-2002-07.html
1160n/a #
1161n/a # zlib 1.1.4 is fixed, but at least one vendor (RedHat) has decided to
1162n/a # patch its zlib 1.1.3 package instead of upgrading to 1.1.4. For
1163n/a # now, we still accept 1.1.3, because we think it's difficult to
1164n/a # exploit this in Python, and we'd rather make it RedHat's problem
1165n/a # than our problem <wink>.
1166n/a #
1167n/a # You can upgrade zlib to version 1.1.4 yourself by going to
1168n/a # http://www.gzip.org/zlib/
1169n/a zlib_inc = find_file('zlib.h', [], inc_dirs)
1170n/a have_zlib = False
1171n/a if zlib_inc is not None:
1172n/a zlib_h = zlib_inc[0] + '/zlib.h'
1173n/a version = '"0.0.0"'
1174n/a version_req = '"1.1.3"'
1175n/a fp = open(zlib_h)
1176n/a while 1:
1177n/a line = fp.readline()
1178n/a if not line:
1179n/a break
1180n/a if line.startswith('#define ZLIB_VERSION'):
1181n/a version = line.split()[2]
1182n/a break
1183n/a if version >= version_req:
1184n/a if (self.compiler.find_library_file(lib_dirs, 'z')):
1185n/a if sys.platform == "darwin":
1186n/a zlib_extra_link_args = ('-Wl,-search_paths_first',)
1187n/a else:
1188n/a zlib_extra_link_args = ()
1189n/a exts.append( Extension('zlib', ['zlibmodule.c'],
1190n/a libraries = ['z'],
1191n/a extra_link_args = zlib_extra_link_args))
1192n/a have_zlib = True
1193n/a else:
1194n/a missing.append('zlib')
1195n/a else:
1196n/a missing.append('zlib')
1197n/a else:
1198n/a missing.append('zlib')
1199n/a
1200n/a # Helper module for various ascii-encoders. Uses zlib for an optimized
1201n/a # crc32 if we have it. Otherwise binascii uses its own.
1202n/a if have_zlib:
1203n/a extra_compile_args = ['-DUSE_ZLIB_CRC32']
1204n/a libraries = ['z']
1205n/a extra_link_args = zlib_extra_link_args
1206n/a else:
1207n/a extra_compile_args = []
1208n/a libraries = []
1209n/a extra_link_args = []
1210n/a exts.append( Extension('binascii', ['binascii.c'],
1211n/a extra_compile_args = extra_compile_args,
1212n/a libraries = libraries,
1213n/a extra_link_args = extra_link_args) )
1214n/a
1215n/a # Gustavo Niemeyer's bz2 module.
1216n/a if (self.compiler.find_library_file(lib_dirs, 'bz2')):
1217n/a if sys.platform == "darwin":
1218n/a bz2_extra_link_args = ('-Wl,-search_paths_first',)
1219n/a else:
1220n/a bz2_extra_link_args = ()
1221n/a exts.append( Extension('bz2', ['bz2module.c'],
1222n/a libraries = ['bz2'],
1223n/a extra_link_args = bz2_extra_link_args) )
1224n/a else:
1225n/a missing.append('bz2')
1226n/a
1227n/a # Interface to the Expat XML parser
1228n/a #
1229n/a # Expat was written by James Clark and is now maintained by a group of
1230n/a # developers on SourceForge; see www.libexpat.org for more information.
1231n/a # The pyexpat module was written by Paul Prescod after a prototype by
1232n/a # Jack Jansen. The Expat source is included in Modules/expat/. Usage
1233n/a # of a system shared libexpat.so is possible with --with-system-expat
1234n/a # cofigure option.
1235n/a #
1236n/a # More information on Expat can be found at www.libexpat.org.
1237n/a #
1238n/a if '--with-system-expat' in sysconfig.get_config_var("CONFIG_ARGS"):
1239n/a expat_inc = []
1240n/a define_macros = []
1241n/a expat_lib = ['expat']
1242n/a expat_sources = []
1243n/a else:
1244n/a expat_inc = [os.path.join(os.getcwd(), srcdir, 'Modules', 'expat')]
1245n/a define_macros = [
1246n/a ('HAVE_EXPAT_CONFIG_H', '1'),
1247n/a ]
1248n/a expat_lib = []
1249n/a expat_sources = ['expat/xmlparse.c',
1250n/a 'expat/xmlrole.c',
1251n/a 'expat/xmltok.c']
1252n/a
1253n/a exts.append(Extension('pyexpat',
1254n/a define_macros = define_macros,
1255n/a include_dirs = expat_inc,
1256n/a libraries = expat_lib,
1257n/a sources = ['pyexpat.c'] + expat_sources
1258n/a ))
1259n/a
1260n/a # Fredrik Lundh's cElementTree module. Note that this also
1261n/a # uses expat (via the CAPI hook in pyexpat).
1262n/a
1263n/a if os.path.isfile(os.path.join(srcdir, 'Modules', '_elementtree.c')):
1264n/a define_macros.append(('USE_PYEXPAT_CAPI', None))
1265n/a exts.append(Extension('_elementtree',
1266n/a define_macros = define_macros,
1267n/a include_dirs = expat_inc,
1268n/a libraries = expat_lib,
1269n/a sources = ['_elementtree.c'],
1270n/a ))
1271n/a else:
1272n/a missing.append('_elementtree')
1273n/a
1274n/a # Hye-Shik Chang's CJKCodecs modules.
1275n/a if have_unicode:
1276n/a exts.append(Extension('_multibytecodec',
1277n/a ['cjkcodecs/multibytecodec.c']))
1278n/a for loc in ('kr', 'jp', 'cn', 'tw', 'hk', 'iso2022'):
1279n/a exts.append(Extension('_codecs_%s' % loc,
1280n/a ['cjkcodecs/_codecs_%s.c' % loc]))
1281n/a else:
1282n/a missing.append('_multibytecodec')
1283n/a for loc in ('kr', 'jp', 'cn', 'tw', 'hk', 'iso2022'):
1284n/a missing.append('_codecs_%s' % loc)
1285n/a
1286n/a # Dynamic loading module
1287n/a if sys.maxint == 0x7fffffff:
1288n/a # This requires sizeof(int) == sizeof(long) == sizeof(char*)
1289n/a dl_inc = find_file('dlfcn.h', [], inc_dirs)
1290n/a if (dl_inc is not None) and (platform not in ['atheos']):
1291n/a exts.append( Extension('dl', ['dlmodule.c']) )
1292n/a else:
1293n/a missing.append('dl')
1294n/a else:
1295n/a missing.append('dl')
1296n/a
1297n/a # Thomas Heller's _ctypes module
1298n/a self.detect_ctypes(inc_dirs, lib_dirs)
1299n/a
1300n/a # Richard Oudkerk's multiprocessing module
1301n/a if platform == 'win32': # Windows
1302n/a macros = dict()
1303n/a libraries = ['ws2_32']
1304n/a
1305n/a elif platform == 'darwin': # Mac OSX
1306n/a macros = dict()
1307n/a libraries = []
1308n/a
1309n/a elif platform == 'cygwin': # Cygwin
1310n/a macros = dict()
1311n/a libraries = []
1312n/a
1313n/a elif platform in ('freebsd4', 'freebsd5', 'freebsd6', 'freebsd7', 'freebsd8'):
1314n/a # FreeBSD's P1003.1b semaphore support is very experimental
1315n/a # and has many known problems. (as of June 2008)
1316n/a macros = dict()
1317n/a libraries = []
1318n/a
1319n/a elif platform.startswith('openbsd'):
1320n/a macros = dict()
1321n/a libraries = []
1322n/a
1323n/a elif platform.startswith('netbsd'):
1324n/a macros = dict()
1325n/a libraries = []
1326n/a
1327n/a else: # Linux and other unices
1328n/a macros = dict()
1329n/a libraries = ['rt']
1330n/a
1331n/a if platform == 'win32':
1332n/a multiprocessing_srcs = [ '_multiprocessing/multiprocessing.c',
1333n/a '_multiprocessing/semaphore.c',
1334n/a '_multiprocessing/pipe_connection.c',
1335n/a '_multiprocessing/socket_connection.c',
1336n/a '_multiprocessing/win32_functions.c'
1337n/a ]
1338n/a
1339n/a else:
1340n/a multiprocessing_srcs = [ '_multiprocessing/multiprocessing.c',
1341n/a '_multiprocessing/socket_connection.c'
1342n/a ]
1343n/a if (sysconfig.get_config_var('HAVE_SEM_OPEN') and not
1344n/a sysconfig.get_config_var('POSIX_SEMAPHORES_NOT_ENABLED')):
1345n/a multiprocessing_srcs.append('_multiprocessing/semaphore.c')
1346n/a
1347n/a if sysconfig.get_config_var('WITH_THREAD'):
1348n/a exts.append ( Extension('_multiprocessing', multiprocessing_srcs,
1349n/a define_macros=macros.items(),
1350n/a include_dirs=["Modules/_multiprocessing"]))
1351n/a else:
1352n/a missing.append('_multiprocessing')
1353n/a
1354n/a # End multiprocessing
1355n/a
1356n/a
1357n/a # Platform-specific libraries
1358n/a if platform == 'linux2':
1359n/a # Linux-specific modules
1360n/a exts.append( Extension('linuxaudiodev', ['linuxaudiodev.c']) )
1361n/a else:
1362n/a missing.append('linuxaudiodev')
1363n/a
1364n/a if platform in ('linux2', 'freebsd4', 'freebsd5', 'freebsd6',
1365n/a 'freebsd7', 'freebsd8'):
1366n/a exts.append( Extension('ossaudiodev', ['ossaudiodev.c']) )
1367n/a else:
1368n/a missing.append('ossaudiodev')
1369n/a
1370n/a if platform == 'sunos5':
1371n/a # SunOS specific modules
1372n/a exts.append( Extension('sunaudiodev', ['sunaudiodev.c']) )
1373n/a else:
1374n/a missing.append('sunaudiodev')
1375n/a
1376n/a if platform == 'darwin':
1377n/a # _scproxy
1378n/a exts.append(Extension("_scproxy", [os.path.join(srcdir, "Mac/Modules/_scproxy.c")],
1379n/a extra_link_args= [
1380n/a '-framework', 'SystemConfiguration',
1381n/a '-framework', 'CoreFoundation'
1382n/a ]))
1383n/a
1384n/a
1385n/a if platform == 'darwin' and ("--disable-toolbox-glue" not in
1386n/a sysconfig.get_config_var("CONFIG_ARGS")):
1387n/a
1388n/a if int(os.uname()[2].split('.')[0]) >= 8:
1389n/a # We're on Mac OS X 10.4 or later, the compiler should
1390n/a # support '-Wno-deprecated-declarations'. This will
1391n/a # surpress deprecation warnings for the Carbon extensions,
1392n/a # these extensions wrap the Carbon APIs and even those
1393n/a # parts that are deprecated.
1394n/a carbon_extra_compile_args = ['-Wno-deprecated-declarations']
1395n/a else:
1396n/a carbon_extra_compile_args = []
1397n/a
1398n/a # Mac OS X specific modules.
1399n/a def macSrcExists(name1, name2=''):
1400n/a if not name1:
1401n/a return None
1402n/a names = (name1,)
1403n/a if name2:
1404n/a names = (name1, name2)
1405n/a path = os.path.join(srcdir, 'Mac', 'Modules', *names)
1406n/a return os.path.exists(path)
1407n/a
1408n/a def addMacExtension(name, kwds, extra_srcs=[]):
1409n/a dirname = ''
1410n/a if name[0] == '_':
1411n/a dirname = name[1:].lower()
1412n/a cname = name + '.c'
1413n/a cmodulename = name + 'module.c'
1414n/a # Check for NNN.c, NNNmodule.c, _nnn/NNN.c, _nnn/NNNmodule.c
1415n/a if macSrcExists(cname):
1416n/a srcs = [cname]
1417n/a elif macSrcExists(cmodulename):
1418n/a srcs = [cmodulename]
1419n/a elif macSrcExists(dirname, cname):
1420n/a # XXX(nnorwitz): If all the names ended with module, we
1421n/a # wouldn't need this condition. ibcarbon is the only one.
1422n/a srcs = [os.path.join(dirname, cname)]
1423n/a elif macSrcExists(dirname, cmodulename):
1424n/a srcs = [os.path.join(dirname, cmodulename)]
1425n/a else:
1426n/a raise RuntimeError("%s not found" % name)
1427n/a
1428n/a # Here's the whole point: add the extension with sources
1429n/a exts.append(Extension(name, srcs + extra_srcs, **kwds))
1430n/a
1431n/a # Core Foundation
1432n/a core_kwds = {'extra_compile_args': carbon_extra_compile_args,
1433n/a 'extra_link_args': ['-framework', 'CoreFoundation'],
1434n/a }
1435n/a addMacExtension('_CF', core_kwds, ['cf/pycfbridge.c'])
1436n/a addMacExtension('autoGIL', core_kwds)
1437n/a
1438n/a
1439n/a
1440n/a # Carbon
1441n/a carbon_kwds = {'extra_compile_args': carbon_extra_compile_args,
1442n/a 'extra_link_args': ['-framework', 'Carbon'],
1443n/a }
1444n/a CARBON_EXTS = ['ColorPicker', 'gestalt', 'MacOS', 'Nav',
1445n/a 'OSATerminology', 'icglue',
1446n/a # All these are in subdirs
1447n/a '_AE', '_AH', '_App', '_CarbonEvt', '_Cm', '_Ctl',
1448n/a '_Dlg', '_Drag', '_Evt', '_File', '_Folder', '_Fm',
1449n/a '_Help', '_Icn', '_IBCarbon', '_List',
1450n/a '_Menu', '_Mlte', '_OSA', '_Res', '_Qd', '_Qdoffs',
1451n/a '_Scrap', '_Snd', '_TE',
1452n/a ]
1453n/a for name in CARBON_EXTS:
1454n/a addMacExtension(name, carbon_kwds)
1455n/a
1456n/a # Workaround for a bug in the version of gcc shipped with Xcode 3.
1457n/a # The _Win extension should build just like the other Carbon extensions, but
1458n/a # this actually results in a hard crash of the linker.
1459n/a #
1460n/a if '-arch ppc64' in cflags and '-arch ppc' in cflags:
1461n/a win_kwds = {'extra_compile_args': carbon_extra_compile_args + ['-arch', 'i386', '-arch', 'ppc'],
1462n/a 'extra_link_args': ['-framework', 'Carbon', '-arch', 'i386', '-arch', 'ppc'],
1463n/a }
1464n/a addMacExtension('_Win', win_kwds)
1465n/a else:
1466n/a addMacExtension('_Win', carbon_kwds)
1467n/a
1468n/a
1469n/a # Application Services & QuickTime
1470n/a app_kwds = {'extra_compile_args': carbon_extra_compile_args,
1471n/a 'extra_link_args': ['-framework','ApplicationServices'],
1472n/a }
1473n/a addMacExtension('_Launch', app_kwds)
1474n/a addMacExtension('_CG', app_kwds)
1475n/a
1476n/a exts.append( Extension('_Qt', ['qt/_Qtmodule.c'],
1477n/a extra_compile_args=carbon_extra_compile_args,
1478n/a extra_link_args=['-framework', 'QuickTime',
1479n/a '-framework', 'Carbon']) )
1480n/a
1481n/a
1482n/a self.extensions.extend(exts)
1483n/a
1484n/a # Call the method for detecting whether _tkinter can be compiled
1485n/a self.detect_tkinter(inc_dirs, lib_dirs)
1486n/a
1487n/a if '_tkinter' not in [e.name for e in self.extensions]:
1488n/a missing.append('_tkinter')
1489n/a
1490n/a return missing
1491n/a
1492n/a def detect_tkinter_darwin(self, inc_dirs, lib_dirs):
1493n/a # The _tkinter module, using frameworks. Since frameworks are quite
1494n/a # different the UNIX search logic is not sharable.
1495n/a from os.path import join, exists
1496n/a framework_dirs = [
1497n/a '/Library/Frameworks',
1498n/a '/System/Library/Frameworks/',
1499n/a join(os.getenv('HOME'), '/Library/Frameworks')
1500n/a ]
1501n/a
1502n/a # Find the directory that contains the Tcl.framework and Tk.framework
1503n/a # bundles.
1504n/a # XXX distutils should support -F!
1505n/a for F in framework_dirs:
1506n/a # both Tcl.framework and Tk.framework should be present
1507n/a for fw in 'Tcl', 'Tk':
1508n/a if not exists(join(F, fw + '.framework')):
1509n/a break
1510n/a else:
1511n/a # ok, F is now directory with both frameworks. Continure
1512n/a # building
1513n/a break
1514n/a else:
1515n/a # Tk and Tcl frameworks not found. Normal "unix" tkinter search
1516n/a # will now resume.
1517n/a return 0
1518n/a
1519n/a # For 8.4a2, we must add -I options that point inside the Tcl and Tk
1520n/a # frameworks. In later release we should hopefully be able to pass
1521n/a # the -F option to gcc, which specifies a framework lookup path.
1522n/a #
1523n/a include_dirs = [
1524n/a join(F, fw + '.framework', H)
1525n/a for fw in 'Tcl', 'Tk'
1526n/a for H in 'Headers', 'Versions/Current/PrivateHeaders'
1527n/a ]
1528n/a
1529n/a # For 8.4a2, the X11 headers are not included. Rather than include a
1530n/a # complicated search, this is a hard-coded path. It could bail out
1531n/a # if X11 libs are not found...
1532n/a include_dirs.append('/usr/X11R6/include')
1533n/a frameworks = ['-framework', 'Tcl', '-framework', 'Tk']
1534n/a
1535n/a # All existing framework builds of Tcl/Tk don't support 64-bit
1536n/a # architectures.
1537n/a cflags = sysconfig.get_config_vars('CFLAGS')[0]
1538n/a archs = re.findall('-arch\s+(\w+)', cflags)
1539n/a fp = os.popen("file %s/Tk.framework/Tk | grep 'for architecture'"%(F,))
1540n/a detected_archs = []
1541n/a for ln in fp:
1542n/a a = ln.split()[-1]
1543n/a if a in archs:
1544n/a detected_archs.append(ln.split()[-1])
1545n/a fp.close()
1546n/a
1547n/a for a in detected_archs:
1548n/a frameworks.append('-arch')
1549n/a frameworks.append(a)
1550n/a
1551n/a ext = Extension('_tkinter', ['_tkinter.c', 'tkappinit.c'],
1552n/a define_macros=[('WITH_APPINIT', 1)],
1553n/a include_dirs = include_dirs,
1554n/a libraries = [],
1555n/a extra_compile_args = frameworks[2:],
1556n/a extra_link_args = frameworks,
1557n/a )
1558n/a self.extensions.append(ext)
1559n/a return 1
1560n/a
1561n/a
1562n/a def detect_tkinter(self, inc_dirs, lib_dirs):
1563n/a # The _tkinter module.
1564n/a
1565n/a # Rather than complicate the code below, detecting and building
1566n/a # AquaTk is a separate method. Only one Tkinter will be built on
1567n/a # Darwin - either AquaTk, if it is found, or X11 based Tk.
1568n/a platform = self.get_platform()
1569n/a if (platform == 'darwin' and
1570n/a self.detect_tkinter_darwin(inc_dirs, lib_dirs)):
1571n/a return
1572n/a
1573n/a # Assume we haven't found any of the libraries or include files
1574n/a # The versions with dots are used on Unix, and the versions without
1575n/a # dots on Windows, for detection by cygwin.
1576n/a tcllib = tklib = tcl_includes = tk_includes = None
1577n/a for version in ['8.6', '86', '8.5', '85', '8.4', '84', '8.3', '83',
1578n/a '8.2', '82', '8.1', '81', '8.0', '80']:
1579n/a tklib = self.compiler.find_library_file(lib_dirs,
1580n/a 'tk' + version)
1581n/a tcllib = self.compiler.find_library_file(lib_dirs,
1582n/a 'tcl' + version)
1583n/a if tklib and tcllib:
1584n/a # Exit the loop when we've found the Tcl/Tk libraries
1585n/a break
1586n/a
1587n/a # Now check for the header files
1588n/a if tklib and tcllib:
1589n/a # Check for the include files on Debian and {Free,Open}BSD, where
1590n/a # they're put in /usr/include/{tcl,tk}X.Y
1591n/a dotversion = version
1592n/a if '.' not in dotversion and "bsd" in sys.platform.lower():
1593n/a # OpenBSD and FreeBSD use Tcl/Tk library names like libtcl83.a,
1594n/a # but the include subdirs are named like .../include/tcl8.3.
1595n/a dotversion = dotversion[:-1] + '.' + dotversion[-1]
1596n/a tcl_include_sub = []
1597n/a tk_include_sub = []
1598n/a for dir in inc_dirs:
1599n/a tcl_include_sub += [dir + os.sep + "tcl" + dotversion]
1600n/a tk_include_sub += [dir + os.sep + "tk" + dotversion]
1601n/a tk_include_sub += tcl_include_sub
1602n/a tcl_includes = find_file('tcl.h', inc_dirs, tcl_include_sub)
1603n/a tk_includes = find_file('tk.h', inc_dirs, tk_include_sub)
1604n/a
1605n/a if (tcllib is None or tklib is None or
1606n/a tcl_includes is None or tk_includes is None):
1607n/a self.announce("INFO: Can't locate Tcl/Tk libs and/or headers", 2)
1608n/a return
1609n/a
1610n/a # OK... everything seems to be present for Tcl/Tk.
1611n/a
1612n/a include_dirs = [] ; libs = [] ; defs = [] ; added_lib_dirs = []
1613n/a for dir in tcl_includes + tk_includes:
1614n/a if dir not in include_dirs:
1615n/a include_dirs.append(dir)
1616n/a
1617n/a # Check for various platform-specific directories
1618n/a if platform == 'sunos5':
1619n/a include_dirs.append('/usr/openwin/include')
1620n/a added_lib_dirs.append('/usr/openwin/lib')
1621n/a elif os.path.exists('/usr/X11R6/include'):
1622n/a include_dirs.append('/usr/X11R6/include')
1623n/a added_lib_dirs.append('/usr/X11R6/lib64')
1624n/a added_lib_dirs.append('/usr/X11R6/lib')
1625n/a elif os.path.exists('/usr/X11R5/include'):
1626n/a include_dirs.append('/usr/X11R5/include')
1627n/a added_lib_dirs.append('/usr/X11R5/lib')
1628n/a else:
1629n/a # Assume default location for X11
1630n/a include_dirs.append('/usr/X11/include')
1631n/a added_lib_dirs.append('/usr/X11/lib')
1632n/a
1633n/a # If Cygwin, then verify that X is installed before proceeding
1634n/a if platform == 'cygwin':
1635n/a x11_inc = find_file('X11/Xlib.h', [], include_dirs)
1636n/a if x11_inc is None:
1637n/a return
1638n/a
1639n/a # Check for BLT extension
1640n/a if self.compiler.find_library_file(lib_dirs + added_lib_dirs,
1641n/a 'BLT8.0'):
1642n/a defs.append( ('WITH_BLT', 1) )
1643n/a libs.append('BLT8.0')
1644n/a elif self.compiler.find_library_file(lib_dirs + added_lib_dirs,
1645n/a 'BLT'):
1646n/a defs.append( ('WITH_BLT', 1) )
1647n/a libs.append('BLT')
1648n/a
1649n/a # Add the Tcl/Tk libraries
1650n/a libs.append('tk'+ version)
1651n/a libs.append('tcl'+ version)
1652n/a
1653n/a if platform in ['aix3', 'aix4']:
1654n/a libs.append('ld')
1655n/a
1656n/a # Finally, link with the X11 libraries (not appropriate on cygwin)
1657n/a if platform != "cygwin":
1658n/a libs.append('X11')
1659n/a
1660n/a ext = Extension('_tkinter', ['_tkinter.c', 'tkappinit.c'],
1661n/a define_macros=[('WITH_APPINIT', 1)] + defs,
1662n/a include_dirs = include_dirs,
1663n/a libraries = libs,
1664n/a library_dirs = added_lib_dirs,
1665n/a )
1666n/a self.extensions.append(ext)
1667n/a
1668n/a## # Uncomment these lines if you want to play with xxmodule.c
1669n/a## ext = Extension('xx', ['xxmodule.c'])
1670n/a## self.extensions.append(ext)
1671n/a
1672n/a # XXX handle these, but how to detect?
1673n/a # *** Uncomment and edit for PIL (TkImaging) extension only:
1674n/a # -DWITH_PIL -I../Extensions/Imaging/libImaging tkImaging.c \
1675n/a # *** Uncomment and edit for TOGL extension only:
1676n/a # -DWITH_TOGL togl.c \
1677n/a # *** Uncomment these for TOGL extension only:
1678n/a # -lGL -lGLU -lXext -lXmu \
1679n/a
1680n/a def configure_ctypes_darwin(self, ext):
1681n/a # Darwin (OS X) uses preconfigured files, in
1682n/a # the Modules/_ctypes/libffi_osx directory.
1683n/a srcdir = sysconfig.get_config_var('srcdir')
1684n/a ffi_srcdir = os.path.abspath(os.path.join(srcdir, 'Modules',
1685n/a '_ctypes', 'libffi_osx'))
1686n/a sources = [os.path.join(ffi_srcdir, p)
1687n/a for p in ['ffi.c',
1688n/a 'x86/darwin64.S',
1689n/a 'x86/x86-darwin.S',
1690n/a 'x86/x86-ffi_darwin.c',
1691n/a 'x86/x86-ffi64.c',
1692n/a 'powerpc/ppc-darwin.S',
1693n/a 'powerpc/ppc-darwin_closure.S',
1694n/a 'powerpc/ppc-ffi_darwin.c',
1695n/a 'powerpc/ppc64-darwin_closure.S',
1696n/a ]]
1697n/a
1698n/a # Add .S (preprocessed assembly) to C compiler source extensions.
1699n/a self.compiler.src_extensions.append('.S')
1700n/a
1701n/a include_dirs = [os.path.join(ffi_srcdir, 'include'),
1702n/a os.path.join(ffi_srcdir, 'powerpc')]
1703n/a ext.include_dirs.extend(include_dirs)
1704n/a ext.sources.extend(sources)
1705n/a return True
1706n/a
1707n/a def configure_ctypes(self, ext):
1708n/a if not self.use_system_libffi:
1709n/a if sys.platform == 'darwin':
1710n/a return self.configure_ctypes_darwin(ext)
1711n/a
1712n/a srcdir = sysconfig.get_config_var('srcdir')
1713n/a ffi_builddir = os.path.join(self.build_temp, 'libffi')
1714n/a ffi_srcdir = os.path.abspath(os.path.join(srcdir, 'Modules',
1715n/a '_ctypes', 'libffi'))
1716n/a ffi_configfile = os.path.join(ffi_builddir, 'fficonfig.py')
1717n/a
1718n/a from distutils.dep_util import newer_group
1719n/a
1720n/a config_sources = [os.path.join(ffi_srcdir, fname)
1721n/a for fname in os.listdir(ffi_srcdir)
1722n/a if os.path.isfile(os.path.join(ffi_srcdir, fname))]
1723n/a if self.force or newer_group(config_sources,
1724n/a ffi_configfile):
1725n/a from distutils.dir_util import mkpath
1726n/a mkpath(ffi_builddir)
1727n/a config_args = []
1728n/a
1729n/a # Pass empty CFLAGS because we'll just append the resulting
1730n/a # CFLAGS to Python's; -g or -O2 is to be avoided.
1731n/a cmd = "cd %s && env CFLAGS='' '%s/configure' %s" \
1732n/a % (ffi_builddir, ffi_srcdir, " ".join(config_args))
1733n/a
1734n/a res = os.system(cmd)
1735n/a if res or not os.path.exists(ffi_configfile):
1736n/a print "Failed to configure _ctypes module"
1737n/a return False
1738n/a
1739n/a fficonfig = {}
1740n/a with open(ffi_configfile) as f:
1741n/a exec f in fficonfig
1742n/a
1743n/a # Add .S (preprocessed assembly) to C compiler source extensions.
1744n/a self.compiler.src_extensions.append('.S')
1745n/a
1746n/a include_dirs = [os.path.join(ffi_builddir, 'include'),
1747n/a ffi_builddir,
1748n/a os.path.join(ffi_srcdir, 'src')]
1749n/a extra_compile_args = fficonfig['ffi_cflags'].split()
1750n/a
1751n/a ext.sources.extend(os.path.join(ffi_srcdir, f) for f in
1752n/a fficonfig['ffi_sources'])
1753n/a ext.include_dirs.extend(include_dirs)
1754n/a ext.extra_compile_args.extend(extra_compile_args)
1755n/a return True
1756n/a
1757n/a def detect_ctypes(self, inc_dirs, lib_dirs):
1758n/a self.use_system_libffi = False
1759n/a include_dirs = []
1760n/a extra_compile_args = []
1761n/a extra_link_args = []
1762n/a sources = ['_ctypes/_ctypes.c',
1763n/a '_ctypes/callbacks.c',
1764n/a '_ctypes/callproc.c',
1765n/a '_ctypes/stgdict.c',
1766n/a '_ctypes/cfield.c',
1767n/a '_ctypes/malloc_closure.c']
1768n/a depends = ['_ctypes/ctypes.h']
1769n/a
1770n/a if sys.platform == 'darwin':
1771n/a sources.append('_ctypes/darwin/dlfcn_simple.c')
1772n/a extra_compile_args.append('-DMACOSX')
1773n/a include_dirs.append('_ctypes/darwin')
1774n/a# XXX Is this still needed?
1775n/a## extra_link_args.extend(['-read_only_relocs', 'warning'])
1776n/a
1777n/a elif sys.platform == 'sunos5':
1778n/a # XXX This shouldn't be necessary; it appears that some
1779n/a # of the assembler code is non-PIC (i.e. it has relocations
1780n/a # when it shouldn't. The proper fix would be to rewrite
1781n/a # the assembler code to be PIC.
1782n/a # This only works with GCC; the Sun compiler likely refuses
1783n/a # this option. If you want to compile ctypes with the Sun
1784n/a # compiler, please research a proper solution, instead of
1785n/a # finding some -z option for the Sun compiler.
1786n/a extra_link_args.append('-mimpure-text')
1787n/a
1788n/a elif sys.platform.startswith('hp-ux'):
1789n/a extra_link_args.append('-fPIC')
1790n/a
1791n/a ext = Extension('_ctypes',
1792n/a include_dirs=include_dirs,
1793n/a extra_compile_args=extra_compile_args,
1794n/a extra_link_args=extra_link_args,
1795n/a libraries=[],
1796n/a sources=sources,
1797n/a depends=depends)
1798n/a ext_test = Extension('_ctypes_test',
1799n/a sources=['_ctypes/_ctypes_test.c'])
1800n/a self.extensions.extend([ext, ext_test])
1801n/a
1802n/a if not '--with-system-ffi' in sysconfig.get_config_var("CONFIG_ARGS"):
1803n/a return
1804n/a
1805n/a if sys.platform == 'darwin':
1806n/a # OS X 10.5 comes with libffi.dylib; the include files are
1807n/a # in /usr/include/ffi
1808n/a inc_dirs.append('/usr/include/ffi')
1809n/a
1810n/a ffi_inc = [sysconfig.get_config_var("LIBFFI_INCLUDEDIR")]
1811n/a if not ffi_inc:
1812n/a ffi_inc = find_file('ffi.h', [], inc_dirs)
1813n/a if ffi_inc is not None:
1814n/a ffi_h = ffi_inc[0] + '/ffi.h'
1815n/a fp = open(ffi_h)
1816n/a while 1:
1817n/a line = fp.readline()
1818n/a if not line:
1819n/a ffi_inc = None
1820n/a break
1821n/a if line.startswith('#define LIBFFI_H'):
1822n/a break
1823n/a ffi_lib = None
1824n/a if ffi_inc is not None:
1825n/a for lib_name in ('ffi_convenience', 'ffi_pic', 'ffi'):
1826n/a if (self.compiler.find_library_file(lib_dirs, lib_name)):
1827n/a ffi_lib = lib_name
1828n/a break
1829n/a
1830n/a if ffi_inc and ffi_lib:
1831n/a ext.include_dirs.extend(ffi_inc)
1832n/a ext.libraries.append(ffi_lib)
1833n/a self.use_system_libffi = True
1834n/a
1835n/a
1836n/aclass PyBuildInstall(install):
1837n/a # Suppress the warning about installation into the lib_dynload
1838n/a # directory, which is not in sys.path when running Python during
1839n/a # installation:
1840n/a def initialize_options (self):
1841n/a install.initialize_options(self)
1842n/a self.warn_dir=0
1843n/a
1844n/aclass PyBuildInstallLib(install_lib):
1845n/a # Do exactly what install_lib does but make sure correct access modes get
1846n/a # set on installed directories and files. All installed files with get
1847n/a # mode 644 unless they are a shared library in which case they will get
1848n/a # mode 755. All installed directories will get mode 755.
1849n/a
1850n/a so_ext = sysconfig.get_config_var("SO")
1851n/a
1852n/a def install(self):
1853n/a outfiles = install_lib.install(self)
1854n/a self.set_file_modes(outfiles, 0644, 0755)
1855n/a self.set_dir_modes(self.install_dir, 0755)
1856n/a return outfiles
1857n/a
1858n/a def set_file_modes(self, files, defaultMode, sharedLibMode):
1859n/a if not self.is_chmod_supported(): return
1860n/a if not files: return
1861n/a
1862n/a for filename in files:
1863n/a if os.path.islink(filename): continue
1864n/a mode = defaultMode
1865n/a if filename.endswith(self.so_ext): mode = sharedLibMode
1866n/a log.info("changing mode of %s to %o", filename, mode)
1867n/a if not self.dry_run: os.chmod(filename, mode)
1868n/a
1869n/a def set_dir_modes(self, dirname, mode):
1870n/a if not self.is_chmod_supported(): return
1871n/a os.path.walk(dirname, self.set_dir_modes_visitor, mode)
1872n/a
1873n/a def set_dir_modes_visitor(self, mode, dirname, names):
1874n/a if os.path.islink(dirname): return
1875n/a log.info("changing mode of %s to %o", dirname, mode)
1876n/a if not self.dry_run: os.chmod(dirname, mode)
1877n/a
1878n/a def is_chmod_supported(self):
1879n/a return hasattr(os, 'chmod')
1880n/a
1881n/aSUMMARY = """
1882n/aPython is an interpreted, interactive, object-oriented programming
1883n/alanguage. It is often compared to Tcl, Perl, Scheme or Java.
1884n/a
1885n/aPython combines remarkable power with very clear syntax. It has
1886n/amodules, classes, exceptions, very high level dynamic data types, and
1887n/adynamic typing. There are interfaces to many system calls and
1888n/alibraries, as well as to various windowing systems (X11, Motif, Tk,
1889n/aMac, MFC). New built-in modules are easily written in C or C++. Python
1890n/ais also usable as an extension language for applications that need a
1891n/aprogrammable interface.
1892n/a
1893n/aThe Python implementation is portable: it runs on many brands of UNIX,
1894n/aon Windows, DOS, OS/2, Mac, Amiga... If your favorite system isn't
1895n/alisted here, it may still be supported, if there's a C compiler for
1896n/ait. Ask around on comp.lang.python -- or just try compiling Python
1897n/ayourself.
1898n/a"""
1899n/a
1900n/aCLASSIFIERS = """
1901n/aDevelopment Status :: 6 - Mature
1902n/aLicense :: OSI Approved :: Python Software Foundation License
1903n/aNatural Language :: English
1904n/aProgramming Language :: C
1905n/aProgramming Language :: Python
1906n/aTopic :: Software Development
1907n/a"""
1908n/a
1909n/adef main():
1910n/a # turn off warnings when deprecated modules are imported
1911n/a import warnings
1912n/a warnings.filterwarnings("ignore",category=DeprecationWarning)
1913n/a setup(# PyPI Metadata (PEP 301)
1914n/a name = "Python",
1915n/a version = sys.version.split()[0],
1916n/a url = "http://www.python.org/%s" % sys.version[:3],
1917n/a maintainer = "Guido van Rossum and the Python community",
1918n/a maintainer_email = "python-dev@python.org",
1919n/a description = "A high-level object-oriented programming language",
1920n/a long_description = SUMMARY.strip(),
1921n/a license = "PSF license",
1922n/a classifiers = filter(None, CLASSIFIERS.split("\n")),
1923n/a platforms = ["Many"],
1924n/a
1925n/a # Build info
1926n/a cmdclass = {'build_ext':PyBuildExt, 'install':PyBuildInstall,
1927n/a 'install_lib':PyBuildInstallLib},
1928n/a # The struct module is defined here, because build_ext won't be
1929n/a # called unless there's at least one extension module defined.
1930n/a ext_modules=[Extension('_struct', ['_struct.c'])],
1931n/a
1932n/a # Scripts to install
1933n/a scripts = ['Tools/scripts/pydoc', 'Tools/scripts/idle',
1934n/a 'Tools/scripts/2to3',
1935n/a 'Lib/smtpd.py']
1936n/a )
1937n/a
1938n/a# --install-platlib
1939n/aif __name__ == '__main__':
1940n/a main()