If you want to use Python with other programming languages, a build system is usually needed. A build system is used to automate the processes of compiling, linking, packaging, and deploying software. This chapter will focus on a tool called SCons, which is implement with pure Python. Building scripts of SCons can be highly modularized and reused, and cross-platform as well.
Using a build system involves writing building scripts. Building scripts of SCons can have three parts:
Below is the SConstruct and the SConscript files of an example project. The SConstruct file is:
import os, sys
AddOption('--cc', dest='cc', type=str, action='store', default='gcc',
help='C compiler (SCons tool): gcc, intelc; default is %default')
AddOption('--optimize', dest='optimize', type=int, action='store', default=2,
help='Optimization level; default is %default.')
AddOption('--no-separation', dest='separate', action='store_false',
default=True,
help='Do not separate build and source directories.')
env = Environment(ENV=os.environ, LIBDIR='lib', BINDIR='bin')
env.Tool('mingw' if sys.platform.startswith('win') else 'default')
env.Tool(GetOption('cc'))
env.Tool('cython')
env.Tool('pyext')
env.Append(CFLAGS='-O%s'%GetOption('optimize'))
env.Append(CPPPATH='include/')
env.Append(LIBPATH='lib/')
env['BUILDPREFIX'] = 'build/' if GetOption('separate') else ''
everything = list()
Export('env', 'everything')
SConscript(['SConscript'])
Default(everything)
# vim: set ft=python ff=unix fenc=utf8 ai et sw=4 ts=4 tw=79:
The SConscript file is:
import os
Import('env', 'everything')
if env['BUILDPREFIX']:
for path in Glob('src/*'):
env.VariantDir(env['BUILDPREFIX']+str(path), str(path))
env.VariantDir(env['BUILDPREFIX']+'cython', 'cython')
everything.append(env.StaticLibrary(
'%s/inter_build'%env['LIBDIR'],
[fname for fname in Glob(env['BUILDPREFIX']+'src/*/*.c')
if 'src/bin/' not in str(fname)]
))
for cfn in Glob(env['BUILDPREFIX']+'cython/*.pyx'):
cfn = str(cfn)
modname = os.path.splitext(os.path.basename(cfn))[0]
cython = env.PythonObject(env.Cython(cfn))
pymod = env.SharedLibrary('%s/core'%env['LIBDIR'], cython, LIBPREFIX='')
everything.append(pymod)
cenv = env.Clone()
cenv.Prepend(LIBS='inter_build')
everything.append(cenv.Program(
'%s/inter_build'%env['BINDIR'],
Glob(env['BUILDPREFIX']+'src/bin/*.c')
))
# vim: set ft=python ff=unix fenc=utf8 ai et sw=4 ts=4 tw=79:
SCons tools provide a means to reuse the building code. For example, we can use the SCons tools provided by the Cython team to build your cython code, by copying the files cython.py and pyext.py into the directory site_scons/site_tools inside your project.