Appendix D. Handling Common Tasks

There is a common set of simple tasks that many build configurations rely on as they become more complex. Most build tools have special purpose constructs for performing these tasks, but since SConscript files are Python scripts, you can use more flexible built-in Python services to perform these tasks. This appendix lists a number of these tasks and how to implement them in Python.

Example D-1. Wildcard globbing to create a list of filenames


import glob
files = glob.glob(wildcard)

Example D-2. Filename extension substitution


import os.path
filename = os.path.splitext(filename)[0]+extension

Example D-3. Appending a path prefix to a list of filenames


import os.path
filenames = [os.path.join(prefix, x) for x in filenames]

or in Python 1.5.2:


import os.path
new_filenames = [] 
for x in filenames:
    new_filenames.append(os.path.join(prefix, x))

Example D-4. Substituting a path prefix with another one


if filename.find(old_prefix) == 0:
    filename = filename.replace(old_prefix, new_prefix)

or in Python 1.5.2:


import string
if string.find(filename, old_prefix) == 0:
    filename = string.replace(filename, old_prefix, new_prefix)      

Example D-5. Filtering a filename list to exclude/retain only a specific set of extensions


import os.path
filenames = [x for x in filenames if os.path.splitext(x)[1] in extensions]

or in Python 1.5.2:


import os.path
new_filenames = []
for x in filenames:
    if os.path.splitext(x)[1] in extensions:
        new_filenames.append(x)

Example D-6. The "backtick function": run a shell command and capture the output

import os
output = os.popen(command).read()