setup.py revision 1ab29b2d3c03886da51af55eb05113d6e4de6b41
1# To be fixed:
2#   Implement --disable-modules setting
3
4import sys, os, string, getopt
5from distutils import sysconfig
6from distutils.core import Extension, setup
7from distutils.command.build_ext import build_ext
8
9# This global variable is used to hold the list of modules to be disabled.
10disabled_module_list = []
11
12def find_file(filename, std_dirs, paths):
13    """Searches for the directory where a given file is located,
14    and returns a possibly-empty list of additional directories, or None
15    if the file couldn't be found at all.
16
17    'filename' is the name of a file, such as readline.h or libcrypto.a.
18    'std_dirs' is the list of standard system directories; if the
19        file is found in one of them, no additional directives are needed.
20    'paths' is a list of additional locations to check; if the file is
21        found in one of them, the resulting list will contain the directory.
22    """
23
24    # Check the standard locations
25    for dir in std_dirs:
26        f = os.path.join(dir, filename)
27        if os.path.exists(f): return []
28
29    # Check the additional directories
30    for dir in paths:
31        f = os.path.join(dir, filename)
32        if os.path.exists(f):
33            return [dir]
34
35    # Not found anywhere
36    return None
37
38def find_library_file(compiler, libname, std_dirs, paths):
39    filename = compiler.library_filename(libname, lib_type='shared')
40    result = find_file(filename, std_dirs, paths)
41    if result is not None: return result
42
43    filename = compiler.library_filename(libname, lib_type='static')
44    result = find_file(filename, std_dirs, paths)
45    return result
46
47def module_enabled(extlist, modname):
48    """Returns whether the module 'modname' is present in the list
49    of extensions 'extlist'."""
50    extlist = [ext for ext in extlist if ext.name == modname]
51    return len(extlist)
52
53class PyBuildExt(build_ext):
54
55    def build_extensions(self):
56
57        # Detect which modules should be compiled
58        self.detect_modules()
59
60        # Remove modules that are present on the disabled list
61        self.extensions = [ext for ext in self.extensions
62                           if ext.name not in disabled_module_list]
63
64        # Fix up the autodetected modules, prefixing all the source files
65        # with Modules/ and adding Python's include directory to the path.
66        (srcdir,) = sysconfig.get_config_vars('srcdir')
67
68        #
69        moddir = os.path.join(os.getcwd(), 'Modules', srcdir)
70        moddir = os.path.normpath(moddir)
71        srcdir, tail = os.path.split(moddir)
72        srcdir = os.path.normpath(srcdir)
73        moddir = os.path.normpath(moddir)
74
75        for ext in self.extensions[:]:
76            ext.sources = [ os.path.join(moddir, filename)
77                            for filename in ext.sources ]
78            ext.include_dirs.append( '.' ) # to get config.h
79            ext.include_dirs.append( os.path.join(srcdir, './Include') )
80
81            # If a module has already been built statically,
82            # don't build it here
83            if ext.name in sys.builtin_module_names:
84                self.extensions.remove(ext)
85
86        # When you run "make CC=altcc" or something similar, you really want
87        # those environment variables passed into the setup.py phase.  Here's
88        # a small set of useful ones.
89        compiler = os.environ.get('CC')
90        linker_so = os.environ.get('LDSHARED')
91        args = {}
92        # unfortunately, distutils doesn't let us provide separate C and C++
93        # compilers
94        if compiler is not None:
95            args['compiler_so'] = compiler
96        if linker_so is not None:
97            args['linker_so'] = linker_so + ' -shared'
98        self.compiler.set_executables(**args)
99
100        build_ext.build_extensions(self)
101
102    def detect_modules(self):
103        # Ensure that /usr/local is always used
104        if '/usr/local/lib' not in self.compiler.library_dirs:
105            self.compiler.library_dirs.append('/usr/local/lib')
106        if '/usr/local/include' not in self.compiler.include_dirs:
107            self.compiler.include_dirs.append( '/usr/local/include' )
108
109        # lib_dirs and inc_dirs are used to search for files;
110        # if a file is found in one of those directories, it can
111        # be assumed that no additional -I,-L directives are needed.
112        lib_dirs = self.compiler.library_dirs + ['/lib', '/usr/lib']
113        inc_dirs = ['/usr/include'] + self.compiler.include_dirs
114        exts = []
115
116        # XXX Omitted modules: gl, pure, dl, SGI-specific modules
117
118        #
119        # The following modules are all pretty straightforward, and compile
120        # on pretty much any POSIXish platform.
121        #
122
123        # Some modules that are normally always on:
124        exts.append( Extension('regex', ['regexmodule.c', 'regexpr.c']) )
125        exts.append( Extension('pcre', ['pcremodule.c', 'pypcre.c']) )
126
127        exts.append( Extension('xreadlines', ['xreadlinesmodule.c']) )
128
129        # array objects
130        exts.append( Extension('array', ['arraymodule.c']) )
131        # complex math library functions
132        exts.append( Extension('cmath', ['cmathmodule.c'], libraries=['m']) )
133        # math library functions, e.g. sin()
134        exts.append( Extension('math',  ['mathmodule.c'], libraries=['m']) )
135        # fast string operations implemented in C
136        exts.append( Extension('strop', ['stropmodule.c']) )
137        # time operations and variables
138        exts.append( Extension('time', ['timemodule.c'], libraries=['m']) )
139        # operator.add() and similar goodies
140        exts.append( Extension('operator', ['operator.c']) )
141        # access to the builtin codecs and codec registry
142        exts.append( Extension('_codecs', ['_codecsmodule.c']) )
143        # static Unicode character database
144        exts.append( Extension('unicodedata',
145                               ['unicodedata.c', 'unicodedatabase.c']) )
146        # Unicode Character Name expansion hash table
147        exts.append( Extension('ucnhash', ['ucnhash.c']) )
148        # access to ISO C locale support
149        exts.append( Extension('_locale', ['_localemodule.c']) )
150
151        # Modules with some UNIX dependencies -- on by default:
152        # (If you have a really backward UNIX, select and socket may not be
153        # supported...)
154
155        # fcntl(2) and ioctl(2)
156        exts.append( Extension('fcntl', ['fcntlmodule.c']) )
157        # pwd(3)
158        exts.append( Extension('pwd', ['pwdmodule.c']) )
159        # grp(3)
160        exts.append( Extension('grp', ['grpmodule.c']) )
161        # posix (UNIX) errno values
162        exts.append( Extension('errno', ['errnomodule.c']) )
163        # select(2); not on ancient System V
164        exts.append( Extension('select', ['selectmodule.c']) )
165
166        # The md5 module implements the RSA Data Security, Inc. MD5
167        # Message-Digest Algorithm, described in RFC 1321.  The necessary files
168        # md5c.c and md5.h are included here.
169        exts.append( Extension('md5', ['md5module.c', 'md5c.c']) )
170
171        # The sha module implements the SHA checksum algorithm.
172        # (NIST's Secure Hash Algorithm.)
173        exts.append( Extension('sha', ['shamodule.c']) )
174
175        # Tommy Burnette's 'new' module (creates new empty objects of certain
176        # kinds):
177        exts.append( Extension('new', ['newmodule.c']) )
178
179        # Helper module for various ascii-encoders
180        exts.append( Extension('binascii', ['binascii.c']) )
181
182        # Fred Drake's interface to the Python parser
183        exts.append( Extension('parser', ['parsermodule.c']) )
184
185        # Digital Creations' cStringIO and cPickle
186        exts.append( Extension('cStringIO', ['cStringIO.c']) )
187        exts.append( Extension('cPickle', ['cPickle.c']) )
188
189        # Memory-mapped files (also works on Win32).
190        exts.append( Extension('mmap', ['mmapmodule.c']) )
191
192        # Lance Ellinghaus's modules:
193        # enigma-inspired encryption
194        exts.append( Extension('rotor', ['rotormodule.c']) )
195        # syslog daemon interface
196        exts.append( Extension('syslog', ['syslogmodule.c']) )
197
198        # George Neville-Neil's timing module:
199        exts.append( Extension('timing', ['timingmodule.c']) )
200
201        #
202        # Here ends the simple stuff.  From here on, modules need certain
203        # libraries, are platform-specific, or present other surprises.
204        #
205
206        # Multimedia modules
207        # These don't work for 64-bit platforms!!!
208        # These represent audio samples or images as strings:
209
210        # Disabled on 64-bit platforms
211        if sys.maxint != 9223372036854775807L:
212            # Operations on audio samples
213            exts.append( Extension('audioop', ['audioop.c']) )
214            # Operations on images
215            exts.append( Extension('imageop', ['imageop.c']) )
216            # Read SGI RGB image files (but coded portably)
217            exts.append( Extension('rgbimg', ['rgbimgmodule.c']) )
218
219        # readline
220        if (self.compiler.find_library_file(lib_dirs, 'readline')):
221            exts.append( Extension('readline', ['readline.c'],
222                                   libraries=['readline', 'termcap']) )
223
224        # The crypt module is now disabled by default because it breaks builds
225        # on many systems (where -lcrypt is needed), e.g. Linux (I believe).
226
227        if self.compiler.find_library_file(lib_dirs, 'crypt'):
228            libs = ['crypt']
229        else:
230            libs = []
231        exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) )
232
233        # socket(2)
234        # Detect SSL support for the socket module
235        ssl_incs = find_file('openssl/ssl.h', inc_dirs,
236                             ['/usr/local/ssl/include',
237                              '/usr/contrib/ssl/include/'
238                             ]
239                             )
240        ssl_libs = find_library_file(self.compiler, 'ssl',lib_dirs,
241                                     ['/usr/local/ssl/lib',
242                                      '/usr/contrib/ssl/lib/'
243                                     ] )
244
245        if (ssl_incs is not None and
246            ssl_libs is not None):
247            exts.append( Extension('_socket', ['socketmodule.c'],
248                                   include_dirs = ssl_incs,
249                                   library_dirs = ssl_libs,
250                                   libraries = ['ssl', 'crypto'],
251                                   define_macros = [('USE_SSL',1)] ) )
252        else:
253            exts.append( Extension('_socket', ['socketmodule.c']) )
254
255        # Modules that provide persistent dictionary-like semantics.  You will
256        # probably want to arrange for at least one of them to be available on
257        # your machine, though none are defined by default because of library
258        # dependencies.  The Python module anydbm.py provides an
259        # implementation independent wrapper for these; dumbdbm.py provides
260        # similar functionality (but slower of course) implemented in Python.
261
262        # The standard Unix dbm module:
263        if (self.compiler.find_library_file(lib_dirs, 'ndbm')):
264            exts.append( Extension('dbm', ['dbmmodule.c'],
265                                   libraries = ['ndbm'] ) )
266        else:
267            exts.append( Extension('dbm', ['dbmmodule.c']) )
268
269        # Anthony Baxter's gdbm module.  GNU dbm(3) will require -lgdbm:
270        if (self.compiler.find_library_file(lib_dirs, 'gdbm')):
271            exts.append( Extension('gdbm', ['gdbmmodule.c'],
272                                   libraries = ['gdbm'] ) )
273
274        # Berkeley DB interface.
275        #
276        # This requires the Berkeley DB code, see
277        # ftp://ftp.cs.berkeley.edu/pub/4bsd/db.1.85.tar.gz
278        #
279        # Edit the variables DB and DBPORT to point to the db top directory
280        # and the subdirectory of PORT where you built it.
281        #
282        # (See http://electricrain.com/greg/python/bsddb3/ for an interface to
283        # BSD DB 3.x.)
284
285        # Note: If a db.h file is found by configure, bsddb will be enabled
286        # automatically via Setup.config.in.  It only needs to be enabled here
287        # if it is not automatically enabled there; check the generated
288        # Setup.config before enabling it here.
289
290        db_incs = find_file('db_185.h', inc_dirs, [])
291        if (db_incs is not None and
292            self.compiler.find_library_file(lib_dirs, 'db') ):
293            exts.append( Extension('bsddb', ['bsddbmodule.c'],
294                                   include_dirs = db_incs,
295                                   libraries = ['db'] ) )
296
297        # The mpz module interfaces to the GNU Multiple Precision library.
298        # You need to ftp the GNU MP library.
299        # This was originally written and tested against GMP 1.2 and 1.3.2.
300        # It has been modified by Rob Hooft to work with 2.0.2 as well, but I
301        # haven't tested it recently.   For a more complete module,
302        # refer to pympz.sourceforge.net.
303
304        # A compatible MP library unencombered by the GPL also exists.  It was
305        # posted to comp.sources.misc in volume 40 and is widely available from
306        # FTP archive sites. One URL for it is:
307        # ftp://gatekeeper.dec.com/.b/usenet/comp.sources.misc/volume40/fgmp/part01.Z
308
309        # Anthony Baxter's gdbm module.  GNU dbm(3) will require -lgdbm:
310        if (self.compiler.find_library_file(lib_dirs, 'gmp')):
311            exts.append( Extension('mpz', ['mpzmodule.c'],
312                                   libraries = ['gmp'] ) )
313
314
315        # Unix-only modules
316        if sys.platform not in ['mac', 'win32']:
317            # Steen Lumholt's termios module
318            exts.append( Extension('termios', ['termios.c']) )
319            # Jeremy Hylton's rlimit interface
320            exts.append( Extension('resource', ['resource.c']) )
321
322            if (self.compiler.find_library_file(lib_dirs, 'nsl')):
323                exts.append( Extension('nis', ['nismodule.c'],
324                                       libraries = ['nsl']) )
325
326        # Curses support, requring the System V version of curses, often
327        # provided by the ncurses library.
328        if sys.platform == 'sunos4':
329            include_dirs += ['/usr/5include']
330            lib_dirs += ['/usr/5lib']
331
332        if (self.compiler.find_library_file(lib_dirs, 'ncurses')):
333            curses_libs = ['ncurses']
334            exts.append( Extension('_curses', ['_cursesmodule.c'],
335                                   libraries = curses_libs) )
336        elif (self.compiler.find_library_file(lib_dirs, 'curses')):
337            if (self.compiler.find_library_file(lib_dirs, 'terminfo')):
338                curses_libs = ['curses', 'terminfo']
339            else:
340                curses_libs = ['curses', 'termcap']
341
342            exts.append( Extension('_curses', ['_cursesmodule.c'],
343                                   libraries = curses_libs) )
344
345        # If the curses module is enabled, check for the panel module
346        if (os.path.exists('Modules/_curses_panel.c') and
347            module_enabled(exts, '_curses') and
348            self.compiler.find_library_file(lib_dirs, 'panel')):
349            exts.append( Extension('_curses_panel', ['_curses_panel.c'],
350                                   libraries = ['panel'] + curses_libs) )
351
352
353
354        # Lee Busby's SIGFPE modules.
355        # The library to link fpectl with is platform specific.
356        # Choose *one* of the options below for fpectl:
357
358        if sys.platform == 'irix5':
359            # For SGI IRIX (tested on 5.3):
360            exts.append( Extension('fpectl', ['fpectlmodule.c'],
361                                   libraries=['fpe']) )
362        elif 0: # XXX how to detect SunPro?
363            # For Solaris with SunPro compiler (tested on Solaris 2.5 with SunPro C 4.2):
364            # (Without the compiler you don't have -lsunmath.)
365            #fpectl fpectlmodule.c -R/opt/SUNWspro/lib -lsunmath -lm
366            pass
367        else:
368            # For other systems: see instructions in fpectlmodule.c.
369            #fpectl fpectlmodule.c ...
370            exts.append( Extension('fpectl', ['fpectlmodule.c']) )
371
372
373        # Andrew Kuchling's zlib module.
374        # This require zlib 1.1.3 (or later).
375        # See http://www.cdrom.com/pub/infozip/zlib/
376        if (self.compiler.find_library_file(lib_dirs, 'z')):
377            exts.append( Extension('zlib', ['zlibmodule.c'],
378                                   libraries = ['z']) )
379
380        # Interface to the Expat XML parser
381        #
382        # Expat is written by James Clark and must be downloaded separately
383        # (see below).  The pyexpat module was written by Paul Prescod after a
384        # prototype by Jack Jansen.
385        #
386        # The Expat dist includes Windows .lib and .dll files.  Home page is
387        # at http://www.jclark.com/xml/expat.html, the current production
388        # release is always ftp://ftp.jclark.com/pub/xml/expat.zip.
389        #
390        # EXPAT_DIR, below, should point to the expat/ directory created by
391        # unpacking the Expat source distribution.
392        #
393        # Note: the expat build process doesn't yet build a libexpat.a; you
394        # can do this manually while we try convince the author to add it.  To
395        # do so, cd to EXPAT_DIR, run "make" if you have not done so, then
396        # run:
397        #
398        #    ar cr libexpat.a xmltok/*.o xmlparse/*.o
399        #
400        expat_defs = []
401        expat_incs = find_file('expat.h', inc_dirs, [])
402        if expat_incs is not None:
403            # expat.h was found
404            expat_defs = [('HAVE_EXPAT_H', 1)]
405        else:
406            expat_incs = find_file('xmlparse.h', inc_dirs, [])
407
408        if (expat_incs is not None and
409            self.compiler.find_library_file(lib_dirs, 'expat')):
410            exts.append( Extension('pyexpat', ['pyexpat.c'],
411                                   define_macros = expat_defs,
412                                   libraries = ['expat']) )
413
414        # Platform-specific libraries
415        plat = sys.platform
416        if plat == 'linux2':
417            # Linux-specific modules
418            exts.append( Extension('linuxaudiodev', ['linuxaudiodev.c']) )
419
420        if plat == 'sunos5':
421            # SunOS specific modules
422            exts.append( Extension('sunaudiodev', ['sunaudiodev.c']) )
423
424        self.extensions.extend(exts)
425
426        # Call the method for detecting whether _tkinter can be compiled
427        self.detect_tkinter(inc_dirs, lib_dirs)
428
429
430    def detect_tkinter(self, inc_dirs, lib_dirs):
431        # The _tkinter module.
432        #
433        # The command for _tkinter is long and site specific.  Please
434        # uncomment and/or edit those parts as indicated.  If you don't have a
435        # specific extension (e.g. Tix or BLT), leave the corresponding line
436        # commented out.  (Leave the trailing backslashes in!  If you
437        # experience strange errors, you may want to join all uncommented
438        # lines and remove the backslashes -- the backslash interpretation is
439        # done by the shell's "read" command and it may not be implemented on
440        # every system.
441
442        # Assume we haven't found any of the libraries or include files
443        tcllib = tklib = tcl_includes = tk_includes = None
444        for version in ['8.4', '8.3', '8.2', '8.1', '8.0']:
445             tklib = self.compiler.find_library_file(lib_dirs,
446                                                     'tk' + version )
447             tcllib = self.compiler.find_library_file(lib_dirs,
448                                                      'tcl' + version )
449             if tklib and tcllib:
450                # Exit the loop when we've found the Tcl/Tk libraries
451                break
452
453        # Now check for the header files
454        if tklib and tcllib:
455            # Check for the include files on Debian, where
456            # they're put in /usr/include/{tcl,tk}X.Y
457            debian_tcl_include = ( '/usr/include/tcl' + version )
458            debian_tk_include =  ( '/usr/include/tk'  + version )
459            tcl_includes = find_file('tcl.h', inc_dirs,
460                                     [debian_tcl_include]
461                                     )
462            tk_includes = find_file('tk.h', inc_dirs,
463                                     [debian_tk_include]
464                                     )
465
466        if (tcllib is None or tklib is None and
467            tcl_includes is None or tk_includes is None):
468            # Something's missing, so give up
469            return
470
471        # OK... everything seems to be present for Tcl/Tk.
472
473        include_dirs = [] ; libs = [] ; defs = [] ; added_lib_dirs = []
474        for dir in tcl_includes + tk_includes:
475            if dir not in include_dirs:
476                include_dirs.append(dir)
477
478        # Check for various platform-specific directories
479        if sys.platform == 'sunos5':
480            include_dirs.append('/usr/openwin/include')
481            added_lib_dirs.append('/usr/openwin/lib')
482        elif os.path.exists('/usr/X11R6/include'):
483            include_dirs.append('/usr/X11R6/include')
484            added_lib_dirs.append('/usr/X11R6/lib')
485        elif os.path.exists('/usr/X11R5/include'):
486            include_dirs.append('/usr/X11R5/include')
487            added_lib_dirs.append('/usr/X11R5/lib')
488        else:
489            # Assume default location for X11
490            include_dirs.append('/usr/X11/include')
491            added_lib_dirs.append('/usr/X11/lib')
492
493        # Check for Tix extension
494        if self.compiler.find_library_file(lib_dirs + added_lib_dirs, 'tix4.1.8.0'):
495            defs.append( ('WITH_TIX', 1) )
496            libs.append('tix4.1.8.0')
497
498        # Check for BLT extension
499        if self.compiler.find_library_file(lib_dirs + added_lib_dirs, 'BLT8.0'):
500            defs.append( ('WITH_BLT', 1) )
501            libs.append('BLT8.0')
502
503        # Add the Tcl/Tk libraries
504        libs.append('tk'+version)
505        libs.append('tcl'+version)
506
507        if sys.platform in ['aix3', 'aix4']:
508            libs.append('ld')
509
510        # Finally, link with the X11 libraries
511        libs.append('X11')
512
513        ext = Extension('_tkinter', ['_tkinter.c', 'tkappinit.c'],
514                        define_macros=[('WITH_APPINIT', 1)] + defs,
515                        include_dirs = include_dirs,
516                        libraries = libs,
517                        library_dirs = added_lib_dirs,
518                        )
519        self.extensions.append(ext)
520
521        # XXX handle these, but how to detect?
522        # *** Uncomment and edit for PIL (TkImaging) extension only:
523        #	-DWITH_PIL -I../Extensions/Imaging/libImaging  tkImaging.c \
524        # *** Uncomment and edit for TOGL extension only:
525        #	-DWITH_TOGL togl.c \
526        # *** Uncomment these for TOGL extension only:
527        #	-lGL -lGLU -lXext -lXmu \
528
529def main():
530    setup(name = 'Python standard library',
531          version = '%d.%d' % sys.version_info[:2],
532          cmdclass = {'build_ext':PyBuildExt},
533          # The struct module is defined here, because build_ext won't be
534          # called unless there's at least one extension module defined.
535          ext_modules=[Extension('struct', ['structmodule.c'])]
536        )
537
538# --install-platlib
539if __name__ == '__main__':
540    sysconfig.set_python_build()
541    main()
542