setup.py revision 5aa3c4af76a1ed08cf275bb049cfa3ebe9758386
1# Autodetecting setup.py script for building the Python extensions
2#
3
4__version__ = "$Revision$"
5
6import sys, os, getopt
7from distutils import sysconfig
8from distutils import text_file
9from distutils.errors import *
10from distutils.core import Extension, setup
11from distutils.command.build_ext import build_ext
12from distutils.command.install import install
13
14# This global variable is used to hold the list of modules to be disabled.
15disabled_module_list = []
16
17def find_file(filename, std_dirs, paths):
18    """Searches for the directory where a given file is located,
19    and returns a possibly-empty list of additional directories, or None
20    if the file couldn't be found at all.
21
22    'filename' is the name of a file, such as readline.h or libcrypto.a.
23    'std_dirs' is the list of standard system directories; if the
24        file is found in one of them, no additional directives are needed.
25    'paths' is a list of additional locations to check; if the file is
26        found in one of them, the resulting list will contain the directory.
27    """
28
29    # Check the standard locations
30    for dir in std_dirs:
31        f = os.path.join(dir, filename)
32        if os.path.exists(f): return []
33
34    # Check the additional directories
35    for dir in paths:
36        f = os.path.join(dir, filename)
37        if os.path.exists(f):
38            return [dir]
39
40    # Not found anywhere
41    return None
42
43def find_library_file(compiler, libname, std_dirs, paths):
44    filename = compiler.library_filename(libname, lib_type='shared')
45    result = find_file(filename, std_dirs, paths)
46    if result is not None: return result
47
48    filename = compiler.library_filename(libname, lib_type='static')
49    result = find_file(filename, std_dirs, paths)
50    return result
51
52def module_enabled(extlist, modname):
53    """Returns whether the module 'modname' is present in the list
54    of extensions 'extlist'."""
55    extlist = [ext for ext in extlist if ext.name == modname]
56    return len(extlist)
57
58def find_module_file(module, dirlist):
59    """Find a module in a set of possible folders. If it is not found
60    return the unadorned filename"""
61    list = find_file(module, [], dirlist)
62    if not list:
63        return module
64    if len(list) > 1:
65        self.announce("WARNING: multiple copies of %s found"%module)
66    return os.path.join(list[0], module)
67
68class PyBuildExt(build_ext):
69
70    def build_extensions(self):
71
72        # Detect which modules should be compiled
73        self.detect_modules()
74
75        # Remove modules that are present on the disabled list
76        self.extensions = [ext for ext in self.extensions
77                           if ext.name not in disabled_module_list]
78
79        # Fix up the autodetected modules, prefixing all the source files
80        # with Modules/ and adding Python's include directory to the path.
81        (srcdir,) = sysconfig.get_config_vars('srcdir')
82
83        # Figure out the location of the source code for extension modules
84        moddir = os.path.join(os.getcwd(), srcdir, 'Modules')
85        moddir = os.path.normpath(moddir)
86        srcdir, tail = os.path.split(moddir)
87        srcdir = os.path.normpath(srcdir)
88        moddir = os.path.normpath(moddir)
89
90        moddirlist = [moddir]
91        incdirlist = ['./Include']
92
93        # Platform-dependent module source and include directories
94        platform = self.get_platform()
95        if platform == 'darwin1':
96            # Mac OS X also includes some mac-specific modules
97            macmoddir = os.path.join(os.getcwd(), srcdir, 'Mac/Modules')
98            moddirlist.append(macmoddir)
99            incdirlist.append('./Mac/Include')
100
101        # Fix up the paths for scripts, too
102        self.distribution.scripts = [os.path.join(srcdir, filename)
103                                     for filename in self.distribution.scripts]
104
105        for ext in self.extensions[:]:
106            ext.sources = [ find_module_file(filename, moddirlist)
107                            for filename in ext.sources ]
108            ext.include_dirs.append( '.' ) # to get config.h
109            for incdir in incdirlist:
110                ext.include_dirs.append( os.path.join(srcdir, incdir) )
111
112            # If a module has already been built statically,
113            # don't build it here
114            if ext.name in sys.builtin_module_names:
115                self.extensions.remove(ext)
116
117        # Parse Modules/Setup to figure out which modules are turned
118        # on in the file.
119        input = text_file.TextFile('Modules/Setup', join_lines=1)
120        remove_modules = []
121        while 1:
122            line = input.readline()
123            if not line: break
124            line = line.split()
125            remove_modules.append( line[0] )
126        input.close()
127
128        for ext in self.extensions[:]:
129            if ext.name in remove_modules:
130                self.extensions.remove(ext)
131
132        # When you run "make CC=altcc" or something similar, you really want
133        # those environment variables passed into the setup.py phase.  Here's
134        # a small set of useful ones.
135        compiler = os.environ.get('CC')
136        linker_so = os.environ.get('LDSHARED')
137        args = {}
138        # unfortunately, distutils doesn't let us provide separate C and C++
139        # compilers
140        if compiler is not None:
141            (ccshared,opt) = sysconfig.get_config_vars('CCSHARED','OPT')
142            args['compiler_so'] = compiler + ' ' + opt + ' ' + ccshared
143        if linker_so is not None:
144            if platform == 'darwin1':
145                args['linker_so'] = linker_so
146            else:
147                args['linker_so'] = linker_so + ' -shared'
148        self.compiler.set_executables(**args)
149
150        build_ext.build_extensions(self)
151
152    def build_extension(self, ext):
153
154        try:
155            build_ext.build_extension(self, ext)
156        except (CCompilerError, DistutilsError), why:
157            self.announce('WARNING: building of extension "%s" failed: %s' %
158                          (ext.name, sys.exc_info()[1]))
159            return
160        try:
161            __import__(ext.name)
162        except ImportError:
163            self.announce('WARNING: removing "%s" since importing it failed' %
164                          ext.name)
165            assert not self.inplace
166            fullname = self.get_ext_fullname(ext.name)
167            ext_filename = os.path.join(self.build_lib,
168                                        self.get_ext_filename(fullname))
169            os.remove(ext_filename)
170
171    def get_platform (self):
172        # Get value of sys.platform
173        platform = sys.platform
174        if platform[:6] =='cygwin':
175            platform = 'cygwin'
176        elif platform[:4] =='beos':
177            platform = 'beos'
178
179        return platform
180
181    def detect_modules(self):
182        # Ensure that /usr/local is always used
183        if '/usr/local/lib' not in self.compiler.library_dirs:
184            self.compiler.library_dirs.insert(0, '/usr/local/lib')
185        if '/usr/local/include' not in self.compiler.include_dirs:
186            self.compiler.include_dirs.insert(0, '/usr/local/include' )
187
188        # lib_dirs and inc_dirs are used to search for files;
189        # if a file is found in one of those directories, it can
190        # be assumed that no additional -I,-L directives are needed.
191        lib_dirs = self.compiler.library_dirs + ['/lib', '/usr/lib']
192        inc_dirs = self.compiler.include_dirs + ['/usr/include']
193        exts = []
194
195        platform = self.get_platform()
196
197        # Check for MacOS X, which doesn't need libm.a at all
198        math_libs = ['m']
199        if platform in ['Darwin1.2', 'beos']:
200            math_libs = []
201
202        # XXX Omitted modules: gl, pure, dl, SGI-specific modules
203
204        #
205        # The following modules are all pretty straightforward, and compile
206        # on pretty much any POSIXish platform.
207        #
208
209        # Some modules that are normally always on:
210        exts.append( Extension('regex', ['regexmodule.c', 'regexpr.c']) )
211        exts.append( Extension('pcre', ['pcremodule.c', 'pypcre.c']) )
212
213        exts.append( Extension('_weakref', ['_weakref.c']) )
214        exts.append( Extension('_symtable', ['symtablemodule.c']) )
215        exts.append( Extension('xreadlines', ['xreadlinesmodule.c']) )
216
217        # array objects
218        exts.append( Extension('array', ['arraymodule.c']) )
219        # complex math library functions
220        exts.append( Extension('cmath', ['cmathmodule.c'],
221                               libraries=math_libs) )
222
223        # math library functions, e.g. sin()
224        exts.append( Extension('math',  ['mathmodule.c'],
225                               libraries=math_libs) )
226        # fast string operations implemented in C
227        exts.append( Extension('strop', ['stropmodule.c']) )
228        # time operations and variables
229        exts.append( Extension('time', ['timemodule.c'],
230                               libraries=math_libs) )
231        # operator.add() and similar goodies
232        exts.append( Extension('operator', ['operator.c']) )
233        # access to the builtin codecs and codec registry
234        exts.append( Extension('_codecs', ['_codecsmodule.c']) )
235        # Python C API test module
236        exts.append( Extension('_testcapi', ['_testcapimodule.c']) )
237        # static Unicode character database
238        exts.append( Extension('unicodedata', ['unicodedata.c']) )
239        # access to ISO C locale support
240        exts.append( Extension('_locale', ['_localemodule.c']) )
241
242        # Modules with some UNIX dependencies -- on by default:
243        # (If you have a really backward UNIX, select and socket may not be
244        # supported...)
245
246        # fcntl(2) and ioctl(2)
247        exts.append( Extension('fcntl', ['fcntlmodule.c']) )
248        # pwd(3)
249        exts.append( Extension('pwd', ['pwdmodule.c']) )
250        # grp(3)
251        exts.append( Extension('grp', ['grpmodule.c']) )
252        # posix (UNIX) errno values
253        exts.append( Extension('errno', ['errnomodule.c']) )
254        # select(2); not on ancient System V
255        exts.append( Extension('select', ['selectmodule.c']) )
256
257        # The md5 module implements the RSA Data Security, Inc. MD5
258        # Message-Digest Algorithm, described in RFC 1321.  The necessary files
259        # md5c.c and md5.h are included here.
260        exts.append( Extension('md5', ['md5module.c', 'md5c.c']) )
261
262        # The sha module implements the SHA checksum algorithm.
263        # (NIST's Secure Hash Algorithm.)
264        exts.append( Extension('sha', ['shamodule.c']) )
265
266        # Tommy Burnette's 'new' module (creates new empty objects of certain
267        # kinds):
268        exts.append( Extension('new', ['newmodule.c']) )
269
270        # Helper module for various ascii-encoders
271        exts.append( Extension('binascii', ['binascii.c']) )
272
273        # Fred Drake's interface to the Python parser
274        exts.append( Extension('parser', ['parsermodule.c']) )
275
276        # Digital Creations' cStringIO and cPickle
277        exts.append( Extension('cStringIO', ['cStringIO.c']) )
278        exts.append( Extension('cPickle', ['cPickle.c']) )
279
280        # Memory-mapped files (also works on Win32).
281        exts.append( Extension('mmap', ['mmapmodule.c']) )
282
283        # Lance Ellinghaus's modules:
284        # enigma-inspired encryption
285        exts.append( Extension('rotor', ['rotormodule.c']) )
286        # syslog daemon interface
287        exts.append( Extension('syslog', ['syslogmodule.c']) )
288
289        # George Neville-Neil's timing module:
290        exts.append( Extension('timing', ['timingmodule.c']) )
291
292        #
293        # Here ends the simple stuff.  From here on, modules need certain
294        # libraries, are platform-specific, or present other surprises.
295        #
296
297        # Multimedia modules
298        # These don't work for 64-bit platforms!!!
299        # These represent audio samples or images as strings:
300
301        # Disabled on 64-bit platforms
302        if sys.maxint != 9223372036854775807L:
303            # Operations on audio samples
304            exts.append( Extension('audioop', ['audioop.c']) )
305            # Operations on images
306            exts.append( Extension('imageop', ['imageop.c']) )
307            # Read SGI RGB image files (but coded portably)
308            exts.append( Extension('rgbimg', ['rgbimgmodule.c']) )
309
310        # readline
311        if self.compiler.find_library_file(lib_dirs, 'readline'):
312            readline_libs = ['readline']
313            if self.compiler.find_library_file(lib_dirs,
314                                                 'ncurses'):
315                readline_libs.append('ncurses')
316            elif self.compiler.find_library_file(lib_dirs +
317                                               ['/usr/lib/termcap'],
318                                               'termcap'):
319                readline_libs.append('termcap')
320            exts.append( Extension('readline', ['readline.c'],
321                                   library_dirs=['/usr/lib/termcap'],
322                                   libraries=readline_libs) )
323
324        # crypt module.
325
326        if self.compiler.find_library_file(lib_dirs, 'crypt'):
327            libs = ['crypt']
328        else:
329            libs = []
330        exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) )
331
332        # socket(2)
333        # Detect SSL support for the socket module
334        ssl_incs = find_file('openssl/ssl.h', inc_dirs,
335                             ['/usr/local/ssl/include',
336                              '/usr/contrib/ssl/include/'
337                             ]
338                             )
339        ssl_libs = find_library_file(self.compiler, 'ssl',lib_dirs,
340                                     ['/usr/local/ssl/lib',
341                                      '/usr/contrib/ssl/lib/'
342                                     ] )
343
344        if (ssl_incs is not None and
345            ssl_libs is not None):
346            exts.append( Extension('_socket', ['socketmodule.c'],
347                                   include_dirs = ssl_incs,
348                                   library_dirs = ssl_libs,
349                                   libraries = ['ssl', 'crypto'],
350                                   define_macros = [('USE_SSL',1)] ) )
351        else:
352            exts.append( Extension('_socket', ['socketmodule.c']) )
353
354        # Modules that provide persistent dictionary-like semantics.  You will
355        # probably want to arrange for at least one of them to be available on
356        # your machine, though none are defined by default because of library
357        # dependencies.  The Python module anydbm.py provides an
358        # implementation independent wrapper for these; dumbdbm.py provides
359        # similar functionality (but slower of course) implemented in Python.
360
361        # The standard Unix dbm module:
362        if platform not in ['cygwin']:
363            if (self.compiler.find_library_file(lib_dirs, 'ndbm')):
364                exts.append( Extension('dbm', ['dbmmodule.c'],
365                                       libraries = ['ndbm'] ) )
366            else:
367                exts.append( Extension('dbm', ['dbmmodule.c']) )
368
369        # Anthony Baxter's gdbm module.  GNU dbm(3) will require -lgdbm:
370        if (self.compiler.find_library_file(lib_dirs, 'gdbm')):
371            exts.append( Extension('gdbm', ['gdbmmodule.c'],
372                                   libraries = ['gdbm'] ) )
373
374        # Berkeley DB interface.
375        #
376        # This requires the Berkeley DB code, see
377        # ftp://ftp.cs.berkeley.edu/pub/4bsd/db.1.85.tar.gz
378        #
379        # Edit the variables DB and DBPORT to point to the db top directory
380        # and the subdirectory of PORT where you built it.
381        #
382        # (See http://electricrain.com/greg/python/bsddb3/ for an interface to
383        # BSD DB 3.x.)
384
385        dblib = []
386        if self.compiler.find_library_file(lib_dirs, 'db'):
387            dblib = ['db']
388
389        db185_incs = find_file('db_185.h', inc_dirs,
390                               ['/usr/include/db3', '/usr/include/db2'])
391        db_inc = find_file('db.h', inc_dirs, ['/usr/include/db1'])
392        if db185_incs is not None:
393            exts.append( Extension('bsddb', ['bsddbmodule.c'],
394                                   include_dirs = db185_incs,
395                                   define_macros=[('HAVE_DB_185_H',1)],
396                                   libraries = dblib ) )
397        elif db_inc is not None:
398            exts.append( Extension('bsddb', ['bsddbmodule.c'],
399                                   include_dirs = db_inc,
400                                   libraries = dblib) )
401
402        # The mpz module interfaces to the GNU Multiple Precision library.
403        # You need to ftp the GNU MP library.
404        # This was originally written and tested against GMP 1.2 and 1.3.2.
405        # It has been modified by Rob Hooft to work with 2.0.2 as well, but I
406        # haven't tested it recently.   For a more complete module,
407        # refer to pympz.sourceforge.net.
408
409        # A compatible MP library unencombered by the GPL also exists.  It was
410        # posted to comp.sources.misc in volume 40 and is widely available from
411        # FTP archive sites. One URL for it is:
412        # ftp://gatekeeper.dec.com/.b/usenet/comp.sources.misc/volume40/fgmp/part01.Z
413
414        if (self.compiler.find_library_file(lib_dirs, 'gmp')):
415            exts.append( Extension('mpz', ['mpzmodule.c'],
416                                   libraries = ['gmp'] ) )
417
418
419        # Unix-only modules
420        if platform not in ['mac', 'win32']:
421            # Steen Lumholt's termios module
422            exts.append( Extension('termios', ['termios.c']) )
423            # Jeremy Hylton's rlimit interface
424            if platform not in ['cygwin']:
425                exts.append( Extension('resource', ['resource.c']) )
426
427            # Sun yellow pages. Some systems have the functions in libc.
428            if platform not in ['cygwin']:
429                if (self.compiler.find_library_file(lib_dirs, 'nsl')):
430                    libs = ['nsl']
431                else:
432                    libs = []
433                exts.append( Extension('nis', ['nismodule.c'],
434                                       libraries = libs) )
435
436        # Curses support, requring the System V version of curses, often
437        # provided by the ncurses library.
438        if platform == 'sunos4':
439            inc_dirs += ['/usr/5include']
440            lib_dirs += ['/usr/5lib']
441
442        if (self.compiler.find_library_file(lib_dirs, 'ncurses')):
443            curses_libs = ['ncurses']
444            exts.append( Extension('_curses', ['_cursesmodule.c'],
445                                   libraries = curses_libs) )
446        elif (self.compiler.find_library_file(lib_dirs, 'curses')):
447            if (self.compiler.find_library_file(lib_dirs, 'terminfo')):
448                curses_libs = ['curses', 'terminfo']
449            else:
450                curses_libs = ['curses', 'termcap']
451
452            exts.append( Extension('_curses', ['_cursesmodule.c'],
453                                   libraries = curses_libs) )
454
455        # If the curses module is enabled, check for the panel module
456        if (os.path.exists('Modules/_curses_panel.c') and
457            module_enabled(exts, '_curses') and
458            self.compiler.find_library_file(lib_dirs, 'panel')):
459            exts.append( Extension('_curses_panel', ['_curses_panel.c'],
460                                   libraries = ['panel'] + curses_libs) )
461
462
463
464        # Lee Busby's SIGFPE modules.
465        # The library to link fpectl with is platform specific.
466        # Choose *one* of the options below for fpectl:
467
468        if platform == 'irix5':
469            # For SGI IRIX (tested on 5.3):
470            exts.append( Extension('fpectl', ['fpectlmodule.c'],
471                                   libraries=['fpe']) )
472        elif 0: # XXX how to detect SunPro?
473            # For Solaris with SunPro compiler (tested on Solaris 2.5 with SunPro C 4.2):
474            # (Without the compiler you don't have -lsunmath.)
475            #fpectl fpectlmodule.c -R/opt/SUNWspro/lib -lsunmath -lm
476            pass
477        else:
478            # For other systems: see instructions in fpectlmodule.c.
479            #fpectl fpectlmodule.c ...
480            exts.append( Extension('fpectl', ['fpectlmodule.c']) )
481
482
483        # Andrew Kuchling's zlib module.
484        # This require zlib 1.1.3 (or later).
485        # See http://www.cdrom.com/pub/infozip/zlib/
486        zlib_inc = find_file('zlib.h', [], inc_dirs)
487        if zlib_inc is not None:
488            zlib_h = zlib_inc[0] + '/zlib.h'
489            version = '"0.0.0"'
490            version_req = '"1.1.3"'
491            fp = open(zlib_h)
492            while 1:
493                line = fp.readline()
494                if not line:
495                    break
496                if line.find('#define ZLIB_VERSION', 0) == 0:
497                    version = line.split()[2]
498                    break
499            if version >= version_req:
500                if (self.compiler.find_library_file(lib_dirs, 'z')):
501                    exts.append( Extension('zlib', ['zlibmodule.c'],
502                                           libraries = ['z']) )
503
504        # Interface to the Expat XML parser
505        #
506        # Expat is written by James Clark and must be downloaded separately
507        # (see below).  The pyexpat module was written by Paul Prescod after a
508        # prototype by Jack Jansen.
509        #
510        # The Expat dist includes Windows .lib and .dll files.  Home page is
511        # at http://www.jclark.com/xml/expat.html, the current production
512        # release is always ftp://ftp.jclark.com/pub/xml/expat.zip.
513        #
514        # EXPAT_DIR, below, should point to the expat/ directory created by
515        # unpacking the Expat source distribution.
516        #
517        # Note: the expat build process doesn't yet build a libexpat.a; you
518        # can do this manually while we try convince the author to add it.  To
519        # do so, cd to EXPAT_DIR, run "make" if you have not done so, then
520        # run:
521        #
522        #    ar cr libexpat.a xmltok/*.o xmlparse/*.o
523        #
524        expat_defs = []
525        expat_incs = find_file('expat.h', inc_dirs, [])
526        if expat_incs is not None:
527            # expat.h was found
528            expat_defs = [('HAVE_EXPAT_H', 1)]
529        else:
530            expat_incs = find_file('xmlparse.h', inc_dirs, [])
531
532        if (expat_incs is not None and
533            self.compiler.find_library_file(lib_dirs, 'expat')):
534            exts.append( Extension('pyexpat', ['pyexpat.c'],
535                                   define_macros = expat_defs,
536                                   libraries = ['expat']) )
537
538        # Platform-specific libraries
539        if platform == 'linux2':
540            # Linux-specific modules
541            exts.append( Extension('linuxaudiodev', ['linuxaudiodev.c']) )
542
543        if platform == 'sunos5':
544            # SunOS specific modules
545            exts.append( Extension('sunaudiodev', ['sunaudiodev.c']) )
546
547        if platform == 'darwin1':
548            # Mac OS X specific modules. These are ported over from MacPython
549            # and still experimental. Some (such as gestalt or icglue) are
550            # already generally useful, some (the GUI ones) really need to
551            # be used from a framework.
552            exts.append( Extension('gestalt', ['gestaltmodule.c']) )
553            exts.append( Extension('MacOS', ['macosmodule.c']) )
554            exts.append( Extension('icglue', ['icgluemodule.c']) )
555            exts.append( Extension('macfs', ['macfsmodule.c', '../Python/getapplbycreator.c']) )
556##            exts.append( Extension('Nav', ['Nav.c']) )
557##            exts.append( Extension('AE', ['ae/AEmodule.c']) )
558##            exts.append( Extension('App', ['app/Appmodule.c']) )
559##            exts.append( Extension('CF', ['cf/CFmodule.c'],
560##            		extra_link_args=['-framework', 'CoreFoundation']) )
561##            exts.append( Extension('Cm', ['cm/Cmmodule.c']) )
562##            exts.append( Extension('Ctl', ['ctl/Ctlmodule.c']) )
563##            exts.append( Extension('Dlg', ['dlg/Dlgmodule.c']) )
564##            exts.append( Extension('Drag', ['drag/Dragmodule.c']) )
565##            exts.append( Extension('Evt', ['evt/Evtmodule.c']) )
566##            exts.append( Extension('Fm', ['fm/Fmmodule.c']) )
567##            exts.append( Extension('Icn', ['icn/Icnmodule.c']) )
568##            exts.append( Extension('List', ['list/Listmodule.c']) )
569##            exts.append( Extension('Menu', ['menu/Menumodule.c']) )
570##            exts.append( Extension('Mlte', ['mlte/Mltemodule.c']) )
571##            exts.append( Extension('Qd', ['qd/Qdmodule.c']) )
572##            exts.append( Extension('Qdoffs', ['qdoffs/Qdoffsmodule.c']) )
573##            exts.append( Extension('Qt', ['qt/Qtmodule.c'],
574##            		extra_link_args=['-framework', 'QuickTime']) )
575##            exts.append( Extension('Res', ['res/Resmodule.c'] ) )
576####            exts.append( Extension('Scrap', ['scrap/Scrapmodule.c']) )
577##            exts.append( Extension('Snd', ['snd/Sndmodule.c']) )
578##            exts.append( Extension('TE', ['te/TEmodule.c']) )
579####            exts.append( Extension('waste', ['waste/wastemodule.c']) )
580##            exts.append( Extension('Win', ['win/Winmodule.c']) )
581
582        self.extensions.extend(exts)
583
584        # Call the method for detecting whether _tkinter can be compiled
585        self.detect_tkinter(inc_dirs, lib_dirs)
586
587
588    def detect_tkinter(self, inc_dirs, lib_dirs):
589        # The _tkinter module.
590
591        # Assume we haven't found any of the libraries or include files
592        # The versions with dots are used on Unix, and the versions without
593        # dots on Windows, for detection by cygwin.
594        tcllib = tklib = tcl_includes = tk_includes = None
595        for version in ['8.4', '84', '8.3', '83', '8.2',
596                        '82', '8.1', '81', '8.0', '80']:
597             tklib = self.compiler.find_library_file(lib_dirs,
598                                                     'tk' + version )
599             tcllib = self.compiler.find_library_file(lib_dirs,
600                                                      'tcl' + version )
601             if tklib and tcllib:
602                # Exit the loop when we've found the Tcl/Tk libraries
603                break
604
605        # Now check for the header files
606        if tklib and tcllib:
607            # Check for the include files on Debian, where
608            # they're put in /usr/include/{tcl,tk}X.Y
609            debian_tcl_include = [ '/usr/include/tcl' + version ]
610            debian_tk_include =  [ '/usr/include/tk'  + version ] + debian_tcl_include
611            tcl_includes = find_file('tcl.h', inc_dirs, debian_tcl_include)
612            tk_includes = find_file('tk.h', inc_dirs, debian_tk_include)
613
614        if (tcllib is None or tklib is None and
615            tcl_includes is None or tk_includes is None):
616            # Something's missing, so give up
617            return
618
619        # OK... everything seems to be present for Tcl/Tk.
620
621        include_dirs = [] ; libs = [] ; defs = [] ; added_lib_dirs = []
622        for dir in tcl_includes + tk_includes:
623            if dir not in include_dirs:
624                include_dirs.append(dir)
625
626        # Check for various platform-specific directories
627        platform = self.get_platform()
628        if platform == 'sunos5':
629            include_dirs.append('/usr/openwin/include')
630            added_lib_dirs.append('/usr/openwin/lib')
631        elif os.path.exists('/usr/X11R6/include'):
632            include_dirs.append('/usr/X11R6/include')
633            added_lib_dirs.append('/usr/X11R6/lib')
634        elif os.path.exists('/usr/X11R5/include'):
635            include_dirs.append('/usr/X11R5/include')
636            added_lib_dirs.append('/usr/X11R5/lib')
637        else:
638            # Assume default location for X11
639            include_dirs.append('/usr/X11/include')
640            added_lib_dirs.append('/usr/X11/lib')
641
642        # Check for BLT extension
643        if self.compiler.find_library_file(lib_dirs + added_lib_dirs, 'BLT8.0'):
644            defs.append( ('WITH_BLT', 1) )
645            libs.append('BLT8.0')
646
647        # Add the Tcl/Tk libraries
648        libs.append('tk'+version)
649        libs.append('tcl'+version)
650
651        if platform in ['aix3', 'aix4']:
652            libs.append('ld')
653
654        # Finally, link with the X11 libraries (not appropriate on cygwin)
655        if platform != "cygwin":
656            libs.append('X11')
657
658        ext = Extension('_tkinter', ['_tkinter.c', 'tkappinit.c'],
659                        define_macros=[('WITH_APPINIT', 1)] + defs,
660                        include_dirs = include_dirs,
661                        libraries = libs,
662                        library_dirs = added_lib_dirs,
663                        )
664        self.extensions.append(ext)
665
666        # XXX handle these, but how to detect?
667        # *** Uncomment and edit for PIL (TkImaging) extension only:
668        #       -DWITH_PIL -I../Extensions/Imaging/libImaging  tkImaging.c \
669        # *** Uncomment and edit for TOGL extension only:
670        #       -DWITH_TOGL togl.c \
671        # *** Uncomment these for TOGL extension only:
672        #       -lGL -lGLU -lXext -lXmu \
673
674class PyBuildInstall(install):
675    # Suppress the warning about installation into the lib_dynload
676    # directory, which is not in sys.path when running Python during
677    # installation:
678    def initialize_options (self):
679        install.initialize_options(self)
680        self.warn_dir=0
681
682def main():
683    # turn off warnings when deprecated modules are imported
684    import warnings
685    warnings.filterwarnings("ignore",category=DeprecationWarning)
686    setup(name = 'Python standard library',
687          version = '%d.%d' % sys.version_info[:2],
688          cmdclass = {'build_ext':PyBuildExt, 'install':PyBuildInstall},
689          # The struct module is defined here, because build_ext won't be
690          # called unless there's at least one extension module defined.
691          ext_modules=[Extension('struct', ['structmodule.c'])],
692
693          # Scripts to install
694          scripts = ['Tools/scripts/pydoc']
695        )
696
697# --install-platlib
698if __name__ == '__main__':
699    sysconfig.set_python_build()
700    main()
701