12.7. Executing an action immediately: the `Execute` Function
Prev | Chapter 12. Platform-Independent File System Manipulation | Next

## 12.7. Executing an action immediately: the `Execute` Function

We've been showing you how to use Action factories in the `Command` function. You can also execute an Action returned by a factory (or actually, any Action) at the time the `SConscript` file is read by using the `Execute` function. For example, if we need to make sure that a directory exists before we build any targets,

    Execute(Mkdir('/tmp/my_temp_directory'))

Notice that this will create the directory while the `SConscript` file is being read:

    % scons
    scons: Reading SConscript files ...
    Mkdir("/tmp/my_temp_directory")
    scons: done reading SConscript files.
    scons: Building targets ...
    scons: `.' is up to date.
    scons: done building targets.

If you're familiar with Python, you may wonder why you would want to use this instead of just calling the native Python `os.mkdir()` function. The advantage here is that the `Mkdir` action will behave appropriately if the user specifies the SCons `-n` or `-q` options--that is, it will print the action but not actually make the directory when `-n` is specified, or make the directory but not print the action when `-q` is specified.

The `Execute` function returns the exit status or return value of the underlying action being executed. It will also print an error message if the action fails and returns a non-zero value. SCons will not, however, actually stop the build if the action fails. If you want the build to stop in response to a failure in an action called by `Execute`, you must do so by explicitly checking the return value and calling the `Exit` function (or a Python equivalent):

    if Execute(Mkdir('/tmp/my_temp_directory')):
        # A problem occurred while making the temp directory.
        Exit(1)

Prev | Up | Next
12.6. Changing File or Directory Permissions: The `Chmod` Factory | Home | Chapter 13. Controlling Removal of Targets