18.4. Builders That Execute Python Functions

In SCons, you don't have to call an external command to build a file. You can, instead, define a Python function that a Builder object can invoke to build your target file (or files). Such a builder function definition looks like:

def build_function(target, source, env):
    # Code to build "target" from "source"
    return None
    

The arguments of a builder function are:

target

A list of Node objects representing the target or targets to be built by this function. The file names of these target(s) may be extracted using the Python str function.

source

A list of Node objects representing the sources to be used by this function to build the targets. The file names of these source(s) may be extracted using the Python str function.

env

The construction environment used for building the target(s). The function may use any of the environment's construction variables in any way to affect how it builds the targets.

The function will be constructed as a SCons FunctionAction and must return a 0 or None value if the target(s) are built successfully. The function may raise an exception or return any non-zero value to indicate that the build is unsuccessful. For more information on Actions see the Action Objects section of the man page.

Once you've defined the Python function that will build your target file, defining a Builder object for it is as simple as specifying the name of the function, instead of an external command, as the Builder's action argument:

def build_function(target, source, env):
    # Code to build "target" from "source"
    return None
bld = Builder(action = build_function,
              suffix = '.foo',
              src_suffix = '.input')
env = Environment(BUILDERS = {'Foo' : bld})
env.Foo('file')
       

And notice that the output changes slightly, reflecting the fact that a Python function, not an external command, is now called to build the target file:

% scons -Q
build_function(["file.foo"], ["file.input"])