Appendix D. Functions and Environment Methods
Prev |  | Next

## Appendix D. Functions and Environment Methods

This appendix contains descriptions of all of the function and construction environment methods in this version of SCons

`Action`(`action, [output, [var, ...]] [key=value, ...]`), `env`.`Action`(`action, [output, [var, ...]] [key=value, ...]`)

  A factory function to create an Action object for the specified `action`. See the manpage section "Action Objects" for a complete explanation of the arguments and behavior.

  Note that the `env.Action` form of the invocation will expand construction variables in any argument strings, including the `action` argument, at the time it is called using the construction variables in the construction environment through which `env.Action` was called. The `Action` global function form delays all variable expansion until the Action object is actually used.

`AddMethod`(`object, function, [name]`), `env`.`AddMethod`(`function, [name]`)

  Adds `function` to an object as a method. `function` will be called with an instance object as the first argument as for other methods. If `name` is given, it is used as the name of the new method, else the name of `function` is used.

  When the global function `AddMethod` is called, the object to add the method to must be passed as the first argument; typically this will be `Environment`, in order to create a method which applies to all construction environments subsequently constructed. When called using the `env.AddMethod` form, the method is added to the specified construction environment only. Added methods propagate through `env.Clone` calls.

  More examples:

      # Function to add must accept an instance argument.
      # The Python convention is to call this 'self'.
      def my_method(self, arg):
          print("my_method() got", arg)

      # Use the global function to add a method to the Environment class:
      AddMethod(Environment, my_method)
      env = Environment()
      env.my_method('arg')

      # Use the optional name argument to set the name of the method:
      env.AddMethod(my_method, 'other_method_name')
      env.other_method_name('another arg')

`AddOption`(`opt_str, ..., attr=value, ...`)

  Adds a local (project-specific) command-line option. One or more `opt_str` values are the strings representing how the option can be called, while the keyword arguments define attributes of the option. For the most part these are the same as for the `OptionParser.add_option` method in the standard Python library module `optparse`, but with a few additional capabilities noted below. See the optparse documentation for a thorough discussion of its option-processing capabilities. All options added through `AddOption` are placed in a special "Local Options" option group.

  In addition to the arguments and values supported by the `optparse` `add_option` method, `AddOption` allows setting the `nargs` keyword value to a string `'?'` (question mark) to indicate that the option argument for that option string may be omitted. If the option string is present on the command line but has no matching option argument, the value of the `const` keyword argument is produced as the value of the option. If the option string is omitted from the command line, the value of the `default` keyword argument is produced, as usual; if there is no `default` keyword argument in the `AddOption` call, `None` is produced.

  `optparse` recognizes abbreviations of long option names, as long as they can be unambiguously resolved. For example, if `add_option` is called to define a `--devicename` option, it will recognize `--device`, `--dev` and so forth as long as there is no other option which could also match to the same abbreviation. Options added via `AddOption` do not support the automatic recognition of abbreviations. Instead, to allow specific abbreviations, include them as synonyms in the `AddOption` call itself.

  Once a new command-line option has been added with `AddOption`, the option value may be accessed using `GetOption` or `env.GetOption`. If the `settable=True` argument was supplied in the `AddOption` call, the value may also be set later using `SetOption` or `env.SetOption`, if conditions in an `SConscript` file require overriding any default value. Note however that a value specified on the command line will always override a value set in an SConscript file.

  Changed in 4.8.0: added the `settable` keyword argument to enable an added option to be settable via `SetOption`.

  Help text for an option is a combination of the string supplied in the `help` keyword argument to `AddOption` and information collected from the other keyword arguments. Such help is displayed if the `-h` command line option is used (but not with `-H`). Help for all local options is displayed under the separate heading Local Options. The options are unsorted - they will appear in the help text in the order in which the `AddOption` calls occur.

  Example:

      AddOption(
          '--prefix',
          dest='prefix',
          nargs=1,
          type='string',
          action='store',
          metavar='DIR',
          help='installation prefix',
      )
      env = Environment(PREFIX=GetOption('prefix'))

  For that example, the following help text would be produced:

      Local Options:
        --prefix=DIR                installation prefix

  Help text for local options may be unavailable if the `Help` function has been called, see the `Help` documentation for details.

  ### Note

  As an artifact of the internal implementation, the behavior of options added by `AddOption` which take option arguments is undefined if whitespace (rather than an `=` sign) is used as the separator on the command line. Users should avoid such usage; it is recommended to add a note to this effect to project documentation if the situation is likely to arise. In addition, if the `nargs` keyword is used to specify more than one following option argument (that is, with a value of `2` or greater), such arguments would necessarily be whitespace separated, triggering the issue. Developers should not use `AddOption` this way. Future versions of SCons will likely forbid such usage.

`AddPostAction`(`target, action`), `env`.`AddPostAction`(`target, action`)

  Arrange for the specified `action` to be performed after the specified `target` has been built. `action` may be an Action object, or anything that can be converted into an Action object. See the manpage section "Action Objects" for a complete explanation.

  When multiple targets are supplied, the action may be called multiple times, once after each action that generates one or more targets in the list.

      foo = Program('foo.c')
      # remove execute permission from binary:
      AddPostAction(foo, Chmod('$TARGET', "a-x"))

  If a `target` is an `Alias`, `action` is associated with the action of the alias, if specified.

`AddPreAction`(`target, action`), `env`.`AddPreAction`(`target, action`)

  Arrange for the specified `action` to be performed before the specified `target` is built. `action` may be an Action object, or anything that can be converted into an Action object. See the manpage section "Action Objects" for a complete explanation.

  When multiple targets are specified, the action(s) may be called multiple times, once before each action that generates one or more targets in the list.

  Note that if any of the targets are built in multiple steps, the action will be invoked just before the action step that specifically generates the specified target(s). It may not always be obvious if the process is multi-step - for example, if you use the `Program` builder to construct an executable program from a `.c` source file, scons builds an intermediate object file first; the pre-action is invoked after this step and just before the link command to generate the executable program binary. Example:

      foo = Program('foo.c')
      AddPreAction(foo, 'echo "Running pre-action"')

      $ scons -Q
      gcc -o foo.o -c foo.c
      echo "Running pre-action"
      Running pre-action
      gcc -o foo foo.o

  If a `target` is an `Alias`, `action` is associated with the action of the alias, if specified.

`Alias`(`alias, [source, [action]]`), `env`.`Alias`(`alias, [source, [action]]`)

  Create an Alias node that can be used as a reference to zero or more other targets, specified by the optional `source` parameter. Aliases provide a way to give a shorter or more descriptive name to specific targets, and to group multiple targets under a single name. The alias name, or an Alias Node object, may be used as a dependency of any other target, including another alias.

  `alias` and `source` may each be a string or Node object, or a list of strings or Node objects; if Nodes are used for `alias` they must be Alias nodes. If `source` is omitted, the alias is created but has no reference; if selected for building this will result in a “Nothing to be done.” message. An empty alias can be used to define the alias in a visible place in the project; it can later be appended to in a subsidiary SConscript file with the actual target(s) to refer to. The optional `action` parameter specifies an action or list of actions that will be executed whenever the any of the alias targets are out-of-date.

  `Alias` can be called for an existing alias, which appends the `alias` and/or `action` arguments to the existing lists for that alias.

  Returns a list of Alias Node objects representing the alias(es), which exist outside of any physical file system. The alias name space is separate from the name space for tangible targets; to avoid confusion do not reuse target names as alias names.

  Examples:

      Alias('install')
      Alias('install', '/usr/bin')
      Alias(['install', 'install-lib'], '/usr/local/lib')

      env.Alias('install', ['/usr/local/bin', '/usr/local/lib'])
      env.Alias('install', ['/usr/local/man'])

      env.Alias('update', ['file1', 'file2'], "update_database $SOURCES")

`AllowSubstExceptions`(`[exception, ...]`)

  Specifies the exceptions that will be ignored when expanding construction variables. By default, any construction variable expansions that generate a `NameError` or `IndexError` exception will expand to a `''` (an empty string) and not cause scons to fail. All exceptions not in the specified list will generate an error message and terminate processing.

  If `AllowSubstExceptions` is called multiple times, each call completely overwrites the previous list of ignored exceptions. Calling it with no arguments means no exceptions will be ignored.

  Example:

      # Requires that all construction variable names exist.
      # (You may wish to do this if you want to enforce strictly
      # that all construction variables must be defined before use.)
      AllowSubstExceptions()

      # Also allow a string containing a zero-division expansion
      # like '${1 / 0}' to evaluate to ''.
      AllowSubstExceptions(IndexError, NameError, ZeroDivisionError)

`AlwaysBuild`(`target, ...`), `env`.`AlwaysBuild`(`target, ...`)

  Marks each given `target` so that it is always assumed to be out-of-date, and will always be rebuilt if needed. Note, however, that `AlwaysBuild` does not add its target(s) to the default target list, so the targets will only be built if they are specified on the command line, or are a dependent of a target specified on the command line--but they will always be built if so specified. Multiple targets can be passed in to a single call to `AlwaysBuild`.

`env`.`Append`(`key=val, [...]`)

  Appends value(s) intelligently to construction variables in `env`. The construction variables and values to add to them are passed as `key=val` pairs (Python keyword arguments). `env.Append` is designed to allow adding values without having to think about the data type of an existing construction variable. Regular Python syntax can also be used to manipulate the construction variable, but for that you may need to know the types involved, for example pure Python lets you directly "add" two lists of strings, but adding a string to a list or a list to a string requires different syntax - things `Append` takes care of. Some pre-defined construction variables do have type expectations based on how SCons will use them: for example `$CPPDEFINES` is often a string or a list of strings, but can also be a list of tuples or a dictionary; while `$LIBEMITTER` is expected to be a callable or list of callables, and `$BUILDERS` is expected to be a dictionary. Consult the documentation for the various construction variables for more details.

  The following descriptions apply to both the `Append` and `Prepend` methods, as well as their Unique variants, with the differences being the insertion point of the added values and whether duplication is allowed.

  `val` can be almost any type. If `env` does not have a construction variable named `key`, then `key` is simply stored with a value of `val`. Otherwise, `val` is combined with the existing value, possibly converting into an appropriate type which can hold the expanded contents. There are a few special cases to be aware of. Normally, when two strings are combined, the result is a new string containing their concatenation (and you are responsible for supplying any needed separation); however, the contents of `$CPPDEFINES` will be post-processed by adding a prefix and/or suffix to each entry when the command line is produced, so SCons keeps them separate - appending a string will result in a separate string entry, not a combined string. For `$CPPDEFINES`. as well as `$LIBS`, and the various `*PATH` variables, SCons will amend the variable by supplying the compiler-specific syntax (e.g. prepending a `-D` or `/D` prefix for `$CPPDEFINES`), so you should omit this syntax when adding values to these variables. Examples (gcc syntax shown in the expansion of `CPPDEFINES`):

      env = Environment(CXXFLAGS="-std=c11", CPPDEFINES="RELEASE")
      print(f"CXXFLAGS = {env['CXXFLAGS']}, CPPDEFINES = {env['CPPDEFINES']}")
      # notice including a leading space in CXXFLAGS addition
      env.Append(CXXFLAGS=" -O", CPPDEFINES="EXTRA")
      print(f"CXXFLAGS = {env['CXXFLAGS']}, CPPDEFINES = {env['CPPDEFINES']}")
      print("CPPDEFINES will expand to", env.subst('$_CPPDEFFLAGS'))

      $ scons -Q
      CXXFLAGS = -std=c11, CPPDEFINES = RELEASE
      CXXFLAGS = -std=c11 -O, CPPDEFINES = deque(['RELEASE', 'EXTRA'])
      CPPDEFINES will expand to -DRELEASE -DEXTRA
      scons: `.' is up to date.

  Because `$CPPDEFINES` is intended for command-line specification of C/C++ preprocessor macros, additional syntax is accepted when adding to it. The preprocessor accepts arguments to predefine a macro name by itself (`-DFOO` for most compilers, `/DFOO` for Microsoft C++), which gives it an implicit value of `1`, or can be given with a replacement value (`-DBAR=TEXT`). SCons follows these rules when adding to `$CPPDEFINES`:

  - A string is split on spaces, giving an easy way to enter multiple macros in one addition. Use an `=` to specify a valued macro.

  - A tuple is treated as a valued macro. Use the value `None` if the macro should not have a value. It is an error to supply more than two elements in such a tuple.

  - A list is processed in order, adding each item without further interpretation. In this case, space-separated strings are not split.

  - A dictionary is processed in order, adding each key-value pair as a valued macro. Use the value `None` if the macro should not have a value.

  Examples:

      env = Environment(CPPDEFINES="FOO")
      print("CPPDEFINES =", env['CPPDEFINES'])
      env.Append(CPPDEFINES="BAR=1")
      print("CPPDEFINES =", env['CPPDEFINES'])
      env.Append(CPPDEFINES=[("OTHER", 2)])
      print("CPPDEFINES =", env['CPPDEFINES'])
      env.Append(CPPDEFINES={"EXTRA": "arg"})
      print("CPPDEFINES =", env['CPPDEFINES'])
      print("CPPDEFINES will expand to", env.subst('$_CPPDEFFLAGS'))

      $ scons -Q
      CPPDEFINES = FOO
      CPPDEFINES = deque(['FOO', 'BAR=1'])
      CPPDEFINES = deque(['FOO', 'BAR=1', ('OTHER', 2)])
      CPPDEFINES = deque(['FOO', 'BAR=1', ('OTHER', 2), ('EXTRA', 'arg')])
      CPPDEFINES will expand to -DFOO -DBAR=1 -DOTHER=2 -DEXTRA=arg
      scons: `.' is up to date.

  Examples of adding multiple macros:

      env = Environment()
      env.Append(CPPDEFINES=[("ONE", 1), "TWO", ("THREE", )])
      print("CPPDEFINES =", env['CPPDEFINES'])
      env.Append(CPPDEFINES={"FOUR": 4, "FIVE": None})
      print("CPPDEFINES =", env['CPPDEFINES'])
      print("CPPDEFINES will expand to", env.subst('$_CPPDEFFLAGS'))

      $ scons -Q
      CPPDEFINES = [('ONE', 1), 'TWO', ('THREE',)]
      CPPDEFINES = deque([('ONE', 1), 'TWO', ('THREE',), ('FOUR', 4), ('FIVE', None)])
      CPPDEFINES will expand to -DONE=1 -DTWO -DTHREE -DFOUR=4 -DFIVE
      scons: `.' is up to date.

  Changed in version 4.5: clarified the use of tuples vs. other types, handling is now consistent across the four functions.

      env = Environment()
      env.Append(CPPDEFINES=("MACRO1", "MACRO2"))
      print("CPPDEFINES =", env['CPPDEFINES'])
      env.Append(CPPDEFINES=[("MACRO3", "MACRO4")])
      print("CPPDEFINES =", env['CPPDEFINES'])
      print("CPPDEFINES will expand to", env.subst('$_CPPDEFFLAGS'))

      $ scons -Q
      CPPDEFINES = ('MACRO1', 'MACRO2')
      CPPDEFINES = deque(['MACRO1', 'MACRO2', ('MACRO3', 'MACRO4')])
      CPPDEFINES will expand to -DMACRO1 -DMACRO2 -DMACRO3=MACRO4
      scons: `.' is up to date.

  See `$CPPDEFINES` for more details.

  Appending a string `val` to a dictionary-typed construction variable enters `val` as the key in the dictionary, and `None` as its value. Using a tuple type to supply a key-value pair only works for the special case of `$CPPDEFINES` described above.

  Although most combinations of types work without needing to know the details, some combinations do not make sense and Python raises an exception.

  When using `env.Append` to modify construction variables which are path specifications (conventionally, the names of such end in `PATH`), it is recommended to add the values as a list of strings, even if you are only adding a single string. The same goes for adding library names to `$LIBS`.

      env.Append(CPPPATH=["#/include"])

  See also `env.AppendUnique`, `env.Prepend` and `env.PrependUnique`.

`env`.`AppendENVPath`(`name, newpath, [envname, sep, delete_existing=False]`)

  Append directory paths from `newpath` to a search-path entry `name` in construction variable `envname` in the current enviromment (`env`). If `envname` is not given, the default is `"ENV"` (see `$ENV`). `envname` is expected to refer to a dictionary-like object; if it does not exist in `env` it will be created as an initially empty dict. `newpath` may be specified as a string, a directory node, or a list of strings. If a string, it may contain multiple paths separated by the system path separator (`os.pathsep`), or, if specified, by the value of `sep`. Top-relative path strings (starting with `#`) are recognized. The type of the existing value of `name` is preserved.

  Paths will only appear once. Duplicate paths in `newpath` are removed, preserving the last occurrence to maintain path order. If `delete_existing` is true (the default), existing duplicates are removed before appending, otherwise, new duplicates are skipped. During comparisons, paths are normalized, to avoid issues with case differences (on case-insensitive filesystems) and with relative paths that may refer back to the same directory. The stored values are not modified by this process.

  Example:

      print('before:', env['ENV']['INCLUDE'])
      include_path = '/foo/bar:/foo'
      env.AppendENVPath('INCLUDE', include_path)
      print('after:', env['ENV']['INCLUDE'])

  Yields:

      before: /foo:/biz
      after: /biz:/foo/bar:/foo

  See also `env.PrependENVPath`.

`env`.`AppendUnique`(`key=val, [...], [delete_existing=False]`)

  Append values to construction variables in the current construction environment, maintaining uniqueness. Works like `env.Append`, except that values that would become duplicates are not added. If `delete_existing` is set to a true value, then for any duplicate, the existing instance of `val` is first removed, then `val` is appended, having the effect of moving it to the end.

  Example:

      env.AppendUnique(CCFLAGS='-g', FOO=['foo.yyy'])

  See also `env.Append`, `env.Prepend` and `env.PrependUnique`.

`Builder`(`action, [arguments]`), `env`.`Builder`(`action, [arguments]`)

  Creates a Builder object for the specified `action`. See the manpage section "Builder Objects" for a complete explanation of the arguments and behavior.

  Note that the `env.Builder`() form of the invocation will expand construction variables in any arguments strings, including the `action` argument, at the time it is called using the construction variables in the `env` construction environment through which `env.Builder` was called. The `Builder` form delays all variable expansion until after the Builder object is actually called.

`CacheDir`(`cache_dir, custom_class=None`), `env`.`CacheDir`(`cache_dir, custom_class=None`)

  Direct scons to maintain a derived-file cache in `cache_dir`. The derived files in the cache will be shared among all the builds specifying the same `cache_dir`. Specifying a `cache_dir` of `None` disables derived file caching.

  Calling the environment method `env.CacheDir` limits the effect to targets built through the specified construction environment. Calling the global function `CacheDir` sets a global default that will be used by all targets built through construction environments that do not set up environment-specific caching by calling `env.CacheDir`.

  Caching behavior can be configured by passing a specialized cache class as the optional `custom_class` parameter. This class must be a subclass of `SCons.CacheDir.CacheDir`. SCons will internally invoke the custom class for performing caching operations. If the parameter is omitted or set to `None`, SCons will use the default `SCons.CacheDir.CacheDir` class.

  When derived-file caching is being used and scons finds a derived file that needs to be rebuilt, it will first look in the cache to see if a file with matching build signature exists (indicating the input file(s) and build action(s) were identical to those for the current target), and if so, will retrieve the file from the cache. scons will report `Retrieved `file' from cache` instead of the normal build message. If the derived file is not present in the cache, scons will build it and then place a copy of the built file in the cache, identified by its build signature, for future use.

  The `Retrieved `file' from cache` messages are useful for human consumption, but less useful when comparing log files between scons runs which will show differences that are noisy and not actually significant. To disable, use the `--cache-show` option. With this option, scons changes printing to always show the action that would have been used to build the file without caching.

  Derived-file caching may be disabled for any invocation of scons by giving the `--cache-disable` command line option; cache updating may be disabled, leaving cache fetching enabled, by giving the `--cache-readonly` option.

  If the `--cache-force` option is used, scons will place a copy of all derived files into the cache, even if they already existed and were not built by this invocation. This is useful to populate a cache the first time a `cache_dir` is used for a build, or to bring a cache up to date after a build with cache updating disabled (`--cache-disable` or `--cache-readonly`) has been done.

  The `NoCache` method can be used to disable caching of specific files. This can be useful if inputs and/or outputs of some tool are impossible to predict or prohibitively large.

  Note that (at this time) SCons provides no facilities for managing the derived-file cache. It is up to the developer to arrange for cache pruning, expiry, access control, etc. if needed.

`Clean`(`targets, files`), `env`.`Clean`(`targets, files`)

  Set additional `files` for removal when any of `targets` are selected for cleaning (`-c` command line option). `targets` and `files` can each be a single filename or node, or a list of filenames or nodes. These can refer to files or directories. Calling this method repeatedly has an additive effect.

  The related `NoClean` method has higher priority: any target specified to `NoClean` will not be cleaned even if also given as a `files` parameter to `Clean`.

  Examples:

      Clean('foo', ['bar', 'baz'])
      Clean('dist', env.Program('hello', 'hello.c'))
      Clean(['foo', 'bar'], 'something_else_to_clean')

  SCons does not directly track directories as targets - they are created if needed and not normally removed in clean mode. In this example, installing the project creates a subdirectory for the documentation. The `Clean` call ensures that the subdirectory is removed if the project is uninstalled.

      Clean(docdir, os.path.join(docdir, projectname))

`env`.`Clone`(`[key=val, ...]`)

  Returns an independent copy of a construction environment. If there are any unrecognized keyword arguments specified, they are added as construction variables in the copy, overwriting any existing values for those keywords. See the manpage section "Construction Environments" for more details.

  Example:

      env2 = env.Clone()
      env3 = env.Clone(CCFLAGS='-g')

  A list of `tools` and a `toolpath` may be specified, as in the `Environment` constructor:

      def MyTool(env):
          env['FOO'] = 'bar'

      env4 = env.Clone(tools=['msvc', MyTool])

  The `parse_flags` keyword argument is also recognized, to allow merging command-line style arguments into the appropriate construction variables (see `env.MergeFlags`).

      # create an environment for compiling programs that use wxWidgets
      wx_env = env.Clone(parse_flags='!wx-config --cflags --cxxflags')

  The `variables` keyword argument is also recognized, to allow (re)initializing construction variables from a `Variables` object.

  Changed in version 4.8.0: the `variables` parameter was added.

`Command`(`target, source, action, [key=val, ...]`), `env`.`Command`(`target, source, action, [key=val, ...]`)

  Creates an anonymous builder and calls it, thus recording `action` to build `target` from `source` into the dependency tree. This can be more convenient for a single special-case build than having to define and add a new named Builder.

  The `Command` function accepts the `source_scanner` and `target_scanner` keyword arguments which are used to specify custom scanners for the specified sources or targets. The value must be a Scanner object. For example, the global `DirScanner` object can be used if any of the sources will be directories that must be scanned on-disk for changes to files that aren't already specified in other Builder or function calls.

  The `Command` function also accepts the `source_factory` and `target_factory` keyword arguments which are used to specify factory functions to create SCons Nodes from any sources or targets specified as strings. If any sources or targets are already Node objects, they are not further transformed even if a factory is specified for them. The default for each is the `Entry` factory.

  These four arguments, if given, are used in the creation of the Builder. Other Builder-specific keyword arguments are not recognized as such. See the manpage section "Builder Objects" for more information about how these arguments work in a Builder.

  Any remaining keyword arguments are passed on to the generated builder when it is called, and behave as described in the manpage section "Builder Methods", in short: recognized arguments have their specified meanings, while the rest are used to override any same-named existing construction variables from the construction environment.

  `action` can be an external command, specified as a string, or a callable Python object; see the manpage section "Action Objects" for more complete information. Also note that a string specifying an external command may be preceded by an at-sign (`@`) to suppress printing the command in question, or by a hyphen (`-`) to ignore the exit status of the external command.

  Examples:

      env.Command(
          target='foo.out',
          source='foo.in',
          action="$FOO_BUILD < $SOURCES > $TARGET"
      )

      env.Command(
          target='bar.out',
          source='bar.in',
          action=["rm -f $TARGET", "$BAR_BUILD < $SOURCES > $TARGET"],
          ENV={'PATH': '/usr/local/bin/'},
      )

      import os
      def rename(env, target, source):
          os.rename('.tmp', target[0])

      env.Command(
          target='baz.out',
          source='baz.in',
          action=["$BAZ_BUILD < $SOURCES > .tmp", rename],
      )

  Note that the `Command` function will usually assume, by default, that the specified targets and/or sources are Files, if no other part of the configuration identifies what type of entries they are. If necessary, you can explicitly specify that targets or source nodes should be treated as directories by using the `Dir` or `env.Dir` functions.

  Examples:

      env.Command('ddd.list', Dir('ddd'), 'ls -l $SOURCE > $TARGET')

      env['DISTDIR'] = 'destination/directory'
      env.Command(env.Dir('$DISTDIR')), None, make_distdir)

  Also note that SCons will usually automatically create any directory necessary to hold a target file, so you normally don't need to create directories by hand.

`Configure`(`env, [custom_tests, conf_dir, log_file, config_h]`), `env`.`Configure`(`[custom_tests, conf_dir, log_file, config_h]`)

  Creates a `Configure` object for integrated functionality similar to GNU autoconf. See the manpage section "Configure Contexts" for a complete explanation of the arguments and behavior.

`DebugOptions`(`[json]`)

  Allows setting options for SCons debug options. Currently, the only supported value is json which sets the path to the JSON file created when `--debug=json` is set.

      DebugOptions(json='#/build/output/scons_stats.json')

  New in version 4.6.0.

`Decider`(`function`), `env`.`Decider`(`function`)

  Specifies that all up-to-date decisions for targets built through this construction environment will be handled by `function`. `function` can be the name of a function or one of the following strings that specify a predefined decider function:

  `"content"`

    Specifies that a target shall be considered out-of-date and rebuilt if the dependency's content has changed since the last time the target was built, as determined by performing a checksum on the dependency's contents using the selected hash function, and comparing it to the checksum recorded the last time the target was built. `content` is the default decider.

    Changed in version 4.1: The decider was renamed to `content` since the hash function is now selectable. The former name, `MD5`, can still be used as a synonym, but is deprecated.

  `"content-timestamp"`

    Specifies that a target shall be considered out-of-date and rebuilt if the dependency's content has changed since the last time the target was built, except that dependencies with a timestamp that matches the last time the target was rebuilt will be assumed to be up-to-date and not rebuilt. This provides behavior very similar to the `content` behavior of always checksumming file contents, with an optimization of not checking the contents of files whose timestamps haven't changed. The drawback is that SCons will not detect if a file's content has changed but its timestamp is the same, as might happen in an automated script that runs a build, updates a file, and runs the build again, all within a single second.

    Changed in version 4.1: The decider was renamed to `content-timestamp` since the hash function is now selectable. The former name, `MD5-timestamp`, can still be used as a synonym, but is deprecated.

  `"timestamp-newer"`

    Specifies that a target shall be considered out-of-date and rebuilt if the dependency's timestamp is newer than the target file's timestamp. This is the behavior of the classic Make utility, and `make` can be used a synonym for `timestamp-newer`.

  `"timestamp-match"`

    Specifies that a target shall be considered out-of-date and rebuilt if the dependency's timestamp is different than the timestamp recorded the last time the target was built. This provides behavior very similar to the classic Make utility (in particular, files are not opened up so that their contents can be checksummed) except that the target will also be rebuilt if a dependency file has been restored to a version with an earlier timestamp, such as can happen when restoring files from backup archives.

  Examples:

      # Use exact timestamp matches by default.
      Decider('timestamp-match')

      # Use hash content signatures for any targets built
      # with the attached construction environment.
      env.Decider('content')

  In addition to the above already-available functions, the `function` argument may be a Python function you supply. Such a function must accept the following four arguments:

  `dependency`

    The Node (file) which should cause the `target` to be rebuilt if it has "changed" since the last time `target` was built.

  `target`

    The Node (file) being built. In the normal case, this is what should get rebuilt if the `dependency` has "changed."

  `prev_ni`

    Stored information about the state of the `dependency` the last time the `target` was built. This can be consulted to match various file characteristics such as the timestamp, size, or content signature.

  `repo_node`

    If set, use this Node instead of the one specified by `dependency` to determine if the dependency has changed. This argument is optional so should be written as a default argument (typically it would be written as `repo_node=None`). A caller will normally only set this if the target only exists in a Repository.

  The `function` should return a value which evaluates `True` if the `dependency` has "changed" since the last time the `target` was built (indicating that the target should be rebuilt), and a value which evaluates `False` otherwise (indicating that the target should not be rebuilt). Note that the decision can be made using whatever criteria are appropriate. Ignoring some or all of the function arguments is perfectly normal.

  Example:

      def my_decider(dependency, target, prev_ni, repo_node=None):
          return not os.path.exists(str(target))

      env.Decider(my_decider)

`Default`(`target[, ...]`), `env`.`Default`(`target[, ...]`)

  Specify default targets to the SCons target selection mechanism. Any call to `Default` will cause SCons to use the defined default target list instead of its built-in algorithm for determining default targets (see the manpage section "Target Selection").

  `target` may be one or more strings, a list of strings, a `NodeList` as returned by a Builder, or `None`. A string `target` may be the name of a file or directory, or a target previously defined by a call to `Alias` (defining the alias later will still create the alias, but it will not be recognized as a default). Calls to `Default` are additive. A `target` of `None` will clear any existing default target list; subsequent calls to `Default` will add to the (now empty) default target list like normal.

  Both forms of this call affect the same global list of default targets; the construction environment method applies construction variable expansion to the targets.

  The current list of targets added using `Default` is available in the `DEFAULT_TARGETS` list (see below).

  Examples:

      Default('foo', 'bar', 'baz')
      env.Default(['a', 'b', 'c'])
      hello = env.Program('hello', 'hello.c')
      env.Default(hello)

`DefaultEnvironment`(`[key=value, ...]`)

  Instantiates and returns the global construction environment object. The Default Environment is used internally by SCons when executing a global function or the global form of a Builder method that requires access to a construction environment.

  On the first call, arguments are interpreted as for the `Environment` function. The Default Environment is a singleton; subsequent calls to `DefaultEnvironment` return the already-constructed object, and any keyword arguments are silently ignored.

  The Default Environment can be modified after instantiation, similar to other construction environments, although some construction environment methods may be unavailable. Modifying the Default Environment has no effect on any other construction environment, either existing or newly constructed.

  It is not necessary to explicitly call `DefaultEnvironment`. SCons instantiates the default environment automatically when the build phase begins, if has not already been done. However, calling it explicitly provides the opportunity to affect and examine its contents. Instantiation occurs even if nothing in the build system appears to use it, due to internal uses.

  If the project `SConscript` files do not use global functions or Builders, a small performance gain may be achieved by calling `DefaultEnvironment` with an empty tools list (`DefaultEnvironment(tools=[])`). This avoids the tool initialization cost for the Default Environment, which is mainly of interest in the test suite where scons is launched repeatedly in a short time period.

`Depends`(`target, dependency`), `env`.`Depends`(`target, dependency`)

  Specifies an explicit dependency; the `target` will be rebuilt whenever the `dependency` has changed. Both the specified `target` and `dependency` can be a string (usually the path name of a file or directory) or Node objects, or a list of strings or Node objects (such as returned by a Builder call). This should only be necessary for cases where the dependency is not caught by a Scanner for the file.

  Example:

      env.Depends('foo', 'other-input-file-for-foo')

      mylib = env.Library('mylib.c')
      installed_lib = env.Install('lib', mylib)
      bar = env.Program('bar.c')

      # Arrange for the library to be copied into the installation
      # directory before trying to build the "bar" program.
      # (Note that this is for example only.  A "real" library
      # dependency would normally be configured through the $LIBS
      # and $LIBPATH variables, not using an env.Depends() call.)

      env.Depends(bar, installed_lib)

`env`.`Detect`(`progs`)

  Find an executable from one or more choices: `progs` may be a string or a list of strings. Returns the first value from `progs` that was found, or `None`. Executable is searched by checking the paths in the execution environment (`env``['ENV']['PATH']`). On Windows systems, additionally applies the filename suffixes found in the execution environment (`env``['ENV']['PATHEXT']`) but will not include any such extension in the return value. `env.Detect` is a wrapper around `env.WhereIs`.

`env`.`Dictionary`(`[var, ...], [as_dict=]`)

  Return an object containing construction variables from `env`. If `var` is omitted, all the construction variables with their values are returned in a dict. If `var` is specified, and `as_dict` is true, the specified construction variables are returned in a dict; otherwise (the default, for backwards compatibility), values only are returned, as a scalar if one `var` is given, or as a list if multiples.

  Example:

      cvars = env.Dictionary()
      cc_values = env.Dictionary('CC', 'CCFLAGS', 'CCCOM')

  ### Note

  The object returned by `env.Dictionary` should be treated as a read-only view into the construction variables. Some construction variables require special internal handling, and modifying them through the `env.Dictionary` object can bypass that handling and cause data inconsistencies. The primary use of `env.Dictionary` is for diagnostic purposes - it is used widely by test cases specifically because it bypasses the special handling so that behavior can be verified.

  Changed in 4.9.0: `as_dict` added.

`Dir`(`name, [directory]`), `env`.`Dir`(`name, [directory]`)

  Returns Directory Node(s). A Directory Node is an object that represents a directory. `name` can be a relative or absolute path or a list of such paths. `directory` is an optional directory that will be used as the parent directory. If no `directory` is specified, the current script's directory is used as the parent.

  If `name` is a single pathname, the corresponding node is returned. If `name` is a list, SCons returns a list of nodes. Construction variables are expanded in `name`.

  Directory Nodes can be used anywhere you would supply a string as a directory name to a Builder method or function. Directory Nodes have attributes and methods that are useful in many situations; see manpage section "Filesystem Nodes" for more information.

`env`.`Dump`(`[var, ...], [format=TYPE]`)

  Serialize construction variables from `env` to a string. If `var` is omitted, all the construction variables are serialized. If one or more `var` values are supplied, only those variables and their values are serialized.

  The optional `format` string selects the serialization format:

  `pretty`

    Returns a pretty-printed representation of the construction variables - the result will look like a Python dict (this is the default).

  `json`

    Returns a JSON-formatted representation of the variables. The variables will be presented as a JSON object literal, the JSON equivalent of a Python dict..

  Changed in 4.9.0: More than one `key` can be specified. The returned string always looks like a dict (or equivalent in other formats); previously a single key serialized only the value, not the key with the value.

  Examples: this `SConstruct`

      env = Environment()
      print(env.Dump('CCCOM'))
      print(env.Dump('CC', 'CCFLAGS', format='json'))

  will print something like:

      {'CCCOM': '$CC -o $TARGET -c $CFLAGS $CCFLAGS $_CCCOMCOM $SOURCES'}
      {
          "CC": "gcc",
          "CCFLAGS": []
      }

  While this `SConstruct`:

      env = Environment()
      print(env.Dump())

  will print something like:

      { 'AR': 'ar',
        'ARCOM': '$AR $ARFLAGS $TARGET $SOURCES\n$RANLIB $RANLIBFLAGS $TARGET',
        'ARFLAGS': ['r'],
        'AS': 'as',
        'ASCOM': '$AS $ASFLAGS -o $TARGET $SOURCES',
        'ASFLAGS': [],
        ...

`EnsurePythonVersion`(`major, minor`)

  Ensure that the Python version is at least `major`.`minor`. This function will print out an error message and exit SCons with a non-zero exit code if the actual Python version is not late enough.

  Example:

      EnsurePythonVersion(2,2)

`EnsureSConsVersion`(`major, minor, [revision]`)

  Ensure that the SCons version is at least `major.minor`, or `major.minor.revision`. if `revision` is specified. This function will print out an error message and exit SCons with a non-zero exit code if the actual SCons version is not late enough.

  Examples:

      EnsureSConsVersion(0,14)

      EnsureSConsVersion(0,96,90)

`Environment`(`[key=value, ...]`), `env`.`Environment`(`[key=value, ...]`)

  Return a new construction environment initialized with the specified `key`=`value` pairs. The keyword arguments `parse_flags`, `platform`, `toolpath`, `tools` and `variables` are specially recognized and do not lead to construction variable creation. See the manpage section "Construction Environments" for more details.

`Execute`(`action, [actionargs ...]`), `env`.`Execute`(`action, [actionargs ...]`)

  Executes an Action. `action` may be an Action object or it may be a command-line string, list of commands, or executable Python function, each of which will first be converted into an Action object and then executed. Any additional arguments to `Execute` are passed on to the `Action` factory function which actually creates the Action object (see the manpage section Action Objects for a description). Example:

      Execute(Copy('file.out', 'file.in'))

  `Execute` performs its action immediately, as part of the SConscript-reading phase. There are no sources or targets declared in an `Execute` call, so any objects it manipulates will not be tracked as part of the SCons dependency graph. In the example above, neither `file.out` nor `file.in` will be tracked objects.

  `Execute` returns the exit value of the command or return value of the Python function. scons prints an error message if the executed `action` fails (exits with or returns a non-zero value), however it does not, automatically terminate the build for such a failure. If you want the build to stop in response to a failed `Execute` call, you must explicitly check for a non-zero return value:

      if Execute("mkdir sub/dir/ectory"):
          # The mkdir failed, don't try to build.
          Exit(1)

`Exit`(`[value]`)

  This tells scons to exit immediately with the specified `value`. A default exit value of `0` (zero) is used if no value is specified.

`Export`(`[vars...], [key=value...]`), `env`.`Export`(`[vars...], [key=value...]`)

  Exports variables for sharing with other SConscript files. The variables are added to a global collection where they can be imported by other SConscript files. `vars` may be one or more strings, or a list of strings. If any string contains whitespace, it is split automatically into individual strings. Each string must match the name of a variable that is in scope during evaluation of the current SConscript file, or an exception is raised.

  A `vars` argument may also be a dictionary or individual keyword arguments; in accordance with Python syntax rules, keyword arguments must come after any non-keyword arguments. The dictionary/keyword form can be used to map the local name of a variable to a different name to be used for imports. See the Examples for an illustration of the syntax.

  `Export` calls are cumulative. Specifying a previously exported variable will replace the previous value in the collection. Both local variables and global variables can be exported.

  To use an exported variable, an SConscript must call `Import` to bring it into its own scope. Importing creates an additional reference to the object that was originally exported, so if that object is mutable, changes made will be visible to other users of that object.

  Examples:

      env = Environment()
      # Make env available for all SConscript files to Import().
      Export("env")

      package = 'my_name'
      # Make env and package available for all SConscript files:.
      Export("env", "package")

      # Make env and package available for all SConscript files:
      Export(["env", "package"])

      # Make env available using the name debug:
      Export(debug=env)

      # Make env available using the name debug:
      Export({"debug": env})

  Note that the `SConscript` function also supports an `exports` argument that allows exporting one or more variables to the SConscript files invoked by that call (only). See the description of that function for details.

`File`(`name, [directory]`), `env`.`File`(`name, [directory]`)

  Returns File Node(s). A File Node is an object that represents a file. `name` can be a relative or absolute path or a list of such paths. `directory` is an optional directory that will be used as the parent directory. If no `directory` is specified, the current script's directory is used as the parent.

  If `name` is a single pathname, the corresponding node is returned. If `name` is a list, SCons returns a list of nodes. Construction variables are expanded in `name`.

  File Nodes can be used anywhere you would supply a string as a file name to a Builder method or function. File Nodes have attributes and methods that are useful in many situations; see manpage section "Filesystem Nodes" for more information.

`FindFile`(`file, dirs`), `env`.`FindFile`(`file, dirs`)

  Search for `file` in the path specified by `dirs`. `dirs` may be a list of directory names or a single directory name. In addition to searching for files that exist in the filesystem, this function also searches for derived files that have not yet been built.

  Example:

      foo = env.FindFile('foo', ['dir1', 'dir2'])

`FindInstalledFiles`(), `env`.`FindInstalledFiles`()

  Returns the list of targets set up by the `Install` or `InstallAs` builders.

  This function serves as a convenient method to select the contents of a binary package.

  Example:

      Install('/bin', ['executable_a', 'executable_b'])

      # will return the file node list
      # ['/bin/executable_a', '/bin/executable_b']
      FindInstalledFiles()

      Install('/lib', ['some_library'])

      # will return the file node list
      # ['/bin/executable_a', '/bin/executable_b', '/lib/some_library']
      FindInstalledFiles()

`FindPathDirs`(`variable`)

  Returns a function (actually a callable Python object) intended to be used as the `path_function` of a Scanner object. The returned object will look up the specified `variable` in a construction environment and treat the construction variable's value as a list of directory paths that should be searched (like `$CPPPATH`, `$LIBPATH`, etc.).

  Note that use of `FindPathDirs` is generally preferable to writing your own `path_function` for the following reasons: 1) The returned list will contain all appropriate directories found in source trees (when `VariantDir` is used) or in code repositories (when `Repository` or the `-Y` option are used). 2) scons will identify expansions of `variable` that evaluate to the same list of directories as, in fact, the same list, and avoid re-scanning the directories for files, when possible.

  Example:

      def my_scan(node, env, path, arg):
          # Code to scan file contents goes here...
          return include_files

      scanner = Scanner(name = 'myscanner',
                        function = my_scan,
                        path_function = FindPathDirs('MYPATH'))

`FindSourceFiles`(`node='"."'`), `env`.`FindSourceFiles`(`node='"."'`)

  Returns the list of nodes which serve as the source of the built files. It does so by inspecting the dependency tree starting at the optional argument `node` which defaults to the '"."'-node. It will then return all leaves of `node`. These are all children which have no further children.

  This function is a convenient method to select the contents of a Source Package.

  Example:

      Program('src/main_a.c')
      Program('src/main_b.c')
      Program('main_c.c')

      # returns ['main_c.c', 'src/main_a.c', 'SConstruct', 'src/main_b.c']
      FindSourceFiles()

      # returns ['src/main_b.c', 'src/main_a.c' ]
      FindSourceFiles('src')

  As you can see, build support files (`SConstruct` in the above example) will also be returned by this function.

`Flatten`(`sequence`), `env`.`Flatten`(`sequence`)

  Takes a sequence (that is, a Python list or tuple) that may contain nested sequences and returns a flattened list containing all of the individual elements in any sequence. This can be helpful for collecting the lists returned by calls to Builders; other Builders will automatically flatten lists specified as input, but direct Python manipulation of these lists does not.

  Examples:

      foo = Object('foo.c')
      bar = Object('bar.c')

      # Because `foo' and `bar' are lists returned by the Object() Builder,
      # `objects' will be a list containing nested lists:
      objects = ['f1.o', foo, 'f2.o', bar, 'f3.o']

      # Passing such a list to another Builder is all right because
      # the Builder will flatten the list automatically:
      Program(source = objects)

      # If you need to manipulate the list directly using Python, you need to
      # call Flatten() yourself, or otherwise handle nested lists:
      for object in Flatten(objects):
          print(str(object))

`GetBuildFailures`()

  Returns a list of exceptions for the actions that failed while attempting to build targets. Each element in the returned list is a `BuildError` object with the following attributes that record various aspects of the build failure:

  `.node` The node that was being built when the build failure occurred.

  `.status` The numeric exit status returned by the command or Python function that failed when trying to build the specified Node.

  `.errstr` The SCons error string describing the build failure. (This is often a generic message like "Error 2" to indicate that an executed command exited with a status of 2.)

  `.filename` The name of the file or directory that actually caused the failure. This may be different from the `.node` attribute. For example, if an attempt to build a target named `sub/dir/target` fails because the `sub/dir` directory could not be created, then the `.node` attribute will be `sub/dir/target` but the `.filename` attribute will be `sub/dir`.

  `.executor` The SCons Executor object for the target Node being built. This can be used to retrieve the construction environment used for the failed action.

  `.action` The actual SCons Action object that failed. This will be one specific action out of the possible list of actions that would have been executed to build the target.

  `.command` The actual expanded command that was executed and failed, after expansion of `$TARGET`, `$SOURCE`, and other construction variables.

  Note that the `GetBuildFailures` function will always return an empty list until any build failure has occurred, which means that `GetBuildFailures` will always return an empty list while the `SConscript` files are being read. Its primary intended use is for functions that will be executed before SCons exits by passing them to the standard Python `atexit.register`() function. Example:

      import atexit

      def print_build_failures():
          from SCons.Script import GetBuildFailures
          for bf in GetBuildFailures():
              print("%s failed: %s" % (bf.node, bf.errstr))

      atexit.register(print_build_failures)

`GetBuildPath`(`file, [...]`), `env`.`GetBuildPath`(`file, [...]`)

  Returns the scons path name (or names) for the specified `file` (or files). The specified `file` or files may be scons Nodes or strings representing path names.

`GetLaunchDir`()

  Returns the absolute path name of the directory from which scons was initially invoked. This can be useful when using the `-u`, `-U` or `-D` options, which internally change to the directory in which the `SConstruct` file is found.

`GetOption`(`name`), `env`.`GetOption`(`name`)

  Query the value of settable option `name`, which may have been set on the command line, via option defaults, or using the `SetOption` function. The value of the option is returned in a type matching how the option was declared - see the documentation of the corresponding command line option for information about each specific option.

  `name` can be an entry from the following table, which shows the corresponding command line arguments that could affect the value. `name` can be also be the destination variable name from a project-specific option added using the `AddOption` function, as long as that addition has been processed prior to the `GetOption` call in the `SConscript` files.

  Query name | Command-line argument | Notes
  --- | --- | ---
  `cache_debug` | `--cache-debug` |
  `cache_disable` | `--cache-disable`, `--no-cache` |
  `cache_force` | `--cache-force`, `--cache-populate` |
  `cache_readonly` | `--cache-readonly` |
  `cache_show` | `--cache-show` |
  `clean` | `-c`, `--clean`, `--remove` |
  `climb_up` | `-D`, `-U`, `-u`, `--up`, `--search_up` |
  `config` | `--config` |
  `debug` | `--debug` |
  `directory` | `-C`, `--directory` |
  `diskcheck` | `--diskcheck` |
  `duplicate` | `--duplicate` |
  `enable_virtualenv` | `--enable-virtualenv` |
  `experimental` | `--experimental` | Since 4.2.
  `file` | `-f`, `--file`, `--makefile`, `--sconstruct` |
  `hash_chunksize` | `--hash-chunksize` | Replaces `md5_chunksize`. Since 4.2
  `hash_format` | `--hash-format` | Since 4.2
  `help` | `-h`, `--help` |
  `ignore_errors` | `-i`, `--ignore-errors` |
  `ignore_virtualenv` | `--ignore-virtualenv` |
  `implicit_cache` | `--implicit-cache` |
  `implicit_deps_changed` | `--implicit-deps-changed` |
  `implicit_deps_unchanged` | `--implicit-deps-unchanged` |
  `include_dir` | `-I`, `--include-dir` |
  `install_sandbox` | `--install-sandbox` | Available only if the `install` tool has been called
  `keep_going` | `-k`, `--keep-going` |
  `max_drift` | `--max-drift` |
  `md5_chunksize` | `--hash-chunksize` | Replaced by `hash_chunksize`. Deprecated since 4.2
  `no_exec` | `-n`, `--no-exec`, `--just-print`, `--dry-run`, `--recon` |
  `no_progress` | `-Q` |
  `num_jobs` | `-j`, `--jobs` |
  `package_type` | `--package-type` | Available only if the `packaging` tool has been called
  `profile_file` | `--profile` |
  `question` | `-q`, `--question` |
  `random` | `--random` |
  `repository` | `-Y`, `--repository`, `--srcdir` |
  `silent` | `-s`, `--silent`, `--quiet` |
  `site_dir` | `--site-dir`, `--no-site-dir` |
  `stack_size` | `--stack-size` |
  `taskmastertrace_file` | `--taskmastertrace` |
  `tree_printers` | `--tree` |
  `warn` | `--warn`, `--warning` |

`GetSConsVersion`()

  Returns the current SCons version in the form of a Tuple[int, int, int], representing the major, minor, and revision values respectively. Added in 4.8.0.

`Glob`(`pattern, [ondisk=True, source=False, strings=False, exclude=None]`), `env`.`Glob`(`pattern, [ondisk=True, source=False, strings=False, exclude=None]`)

  Returns a possibly empty list of Nodes (or strings) that match pathname specification `pattern`. `pattern` can be absolute, top-relative, or (most commonly) relative to the directory of the current `SConscript` file. `Glob` matches both files stored on disk and Nodes which SCons already knows about, even if any corresponding file is not currently stored on disk. The environment method form (`env.Glob`) performs string substitution on `pattern` and returns whatever matches the resulting expanded pattern. The results are sorted, unlike for the similar Python `glob.glob` function, to ensure build order will be stable.

  `pattern` can contain POSIX-style shell metacharacters for matching:

  Pattern | Meaning
  --- | ---
  `*` | matches everything
  `?` | matches any single character
  `[seq]` | matches any character in seq (can be a list or a range).
  `[!seq]` | matches any character not in seq

  For a literal match, wrap the metacharacter in brackets to escape the normal behavior. For example, `'[?]'` matches the character `'?'`.

  Filenames starting with a dot are specially handled - they can only be matched by patterns that start with a dot (or have a dot immediately following a pathname separator character, or slash), they are not not matched by the metacharacters. Metacharacter matches also do not span directory separators.

  `Glob` understands repositories (see the `Repository` function) and source directories (see the `VariantDir` function) and returns a Node (or string, if so configured) match in the local (SConscript) directory if a matching Node is found anywhere in a corresponding repository or source directory.

  If the optional `ondisk` argument evaluates false, the search for matches on disk is disabled, and only matches from already-configured File or Dir Nodes are returned. The default is to return Nodes for matches on disk as well.

  If the optional `source` argument evaluates true, and the local directory is a variant directory, then `Glob` returns Nodes from the corresponding source directory, rather than the local directory.

  If the optional `strings` argument evaluates true, `Glob` returns matches as strings, rather than Nodes. The returned strings will be relative to the local (SConscript) directory. (Note that while this may make it easier to perform arbitrary manipulation of file names, it loses the context SCons would have in the Node, so if the returned strings are passed to a different `SConscript` file, any Node translation there will be relative to that `SConscript` directory, not to the original `SConscript` directory.)

  The optional `exclude` argument may be set to a pattern or a list of patterns describing files or directories to filter out of the match list. Elements matching a least one specified pattern will be excluded. These patterns use the same syntax as for `pattern`.

  Examples:

      Program("foo", Glob("*.c"))
      Zip("/tmp/everything", Glob(".??*") + Glob("*"))
      sources = Glob("*.cpp", exclude=["os_*_specific_*.cpp"]) \
          + Glob("os_%s_specific_*.cpp" % currentOS)

`Help`(`text, append=False, local_only=False`), `env`.`Help`(`text, append=False, local_only=False`)

  Adds `text` to the help message shown when scons is called with the `-h` or `--help` argument.

  On the first call to `Help`, if `append` is `False` (the default), any existing help text is discarded. The default help text is the help for the scons command itself plus help collected from any project-local `AddOption` calls. This is the help printed if `Help` has never been called. If `append` is `True`, `text` is appended to the existing help text. If `local_only` is also `True` (the default is `False`), the project-local help from `AddOption` calls is preserved in the help message but the scons command help is not.

  Subsequent calls to `Help` ignore the keyword arguments `append` and `local_only` and always append to the existing help text.

  Changed in 4.6.0: added `local_only`.

`Ignore`(`target, dependency`), `env`.`Ignore`(`target, dependency`)

  Ignores `dependency` when deciding if `target` needs to be rebuilt. `target` and `dependency` can each be a single filename or Node or a list of filenames or Nodes.

  `Ignore` can also be used to remove a target from the default build by specifying the directory the target will be built in as `target` and the file you want to skip selecting for building as `dependency`. Note that this only removes the target from the default target selection algorithm: if it is a dependency of another object being built SCons still builds it normally. See the third and forth examples below.

  Examples:

      env.Ignore('foo', 'foo.c')
      env.Ignore('bar', ['bar1.h', 'bar2.h'])
      env.Ignore('.', 'foobar.obj')
      env.Ignore('bar', 'bar/foobar.obj')

`Import`(`vars...`), `env`.`Import`(`vars...`)

  Imports variables into the scope of the current SConscript file. `vars` must be strings representing names of variables which have been previously exported either by the `Export` function or by the `exports` argument to the `SConscript` function. Variables exported by the `SConscript` call take precedence. Multiple variable names can be passed to `Import` as separate arguments, as a list of strings, or as words in a space-separated string. The wildcard `"*"` can be used to import all available variables.

  If the imported variable is mutable, changes made locally will be reflected in the object the variable is bound to. This allows subsidiary SConscript files to contribute to building up, for example, a construction environment.

  Examples:

      Import("env")
      Import("env", "variable")
      Import(["env", "variable"])
      Import("*")

`Literal`(`string`), `env`.`Literal`(`string`)

  The specified `string` will be preserved as-is and not have construction variables expanded.

`Local`(`targets`), `env`.`Local`(`targets`)

  The specified `targets` will have copies made in the local tree, even if an already up-to-date copy exists in a repository. Returns a list of the target Node or Nodes.

`env`.`MergeFlags`(`arg, [unique]`)

  Merges values from `arg` into construction variables in `env`. If `arg` is a dictionary, each key-value pair represents a construction variable name and the corresponding flags to merge. If `arg` is not a dictionary, `MergeFlags` attempts to convert it to one before the values are merged. `env.ParseFlags` is used for this, so values to be converted are subject to the same limitations: `ParseFlags` has knowledge of which construction variables certain flags should go to, but not all; and only for GCC and compatible compiler chains. `arg` must be a single object, so to pass multiple strings, enclose them in a list.

  If `unique` is true (the default), duplicate values are not retained. In case of duplication, any construction variable names that end in `PATH` keep the left-most value so the path search order is not altered. All other construction variables keep the right-most value. If `unique` is false, values are appended even if they are duplicates.

  Examples:

      # Add an optimization flag to $CCFLAGS.
      env.MergeFlags({'CCFLAGS': '-O3'})

      # Combine the flags returned from running pkg-config with an optimization
      # flag and merge the result into the construction variables.
      env.MergeFlags(['!pkg-config gtk+-2.0 --cflags', '-O3'])

      # Combine an optimization flag with the flags returned from running pkg-config
      # for two distinct packages and merge into the construction variables.
      env.MergeFlags(
          [
              '-O3',
              '!pkg-config gtk+-2.0 --cflags --libs',
              '!pkg-config libpng12 --cflags --libs',
          ]
      )

`NoCache`(`target, ...`), `env`.`NoCache`(`target, ...`)

  Specifies a list of files which should not be cached whenever the `CacheDir` method has been activated. The specified targets may be a list or an individual target.

  Multiple files should be specified either as separate arguments to the `NoCache` method, or as a list. `NoCache` will also accept the return value of any of the construction environment Builder methods.

  Calling `NoCache` on directories and other non-File Node types has no effect because only File Nodes are cached.

  Examples:

      NoCache('foo.elf')
      NoCache(env.Program('hello', 'hello.c'))

`NoClean`(`targets, ...`), `env`.`NoClean`(`targets, ...`)

  Specifies files or directories which should not be removed whenever a specified `target` (or its dependencies) is selected and clean mode is active (`-c` command line option). `targets` may be one or more file or directory names or nodes, and/or lists of names or nodes. `NoClean` can be called multiple times.

  Calling `NoClean` for a target overrides calling `Clean` for the same target, so any targets passed to both functions will not be removed in clean mode.

  Examples:

      NoClean('foo.elf')
      NoClean(env.Program('hello', 'hello.c'))

`env`.`ParseConfig`(`command, [function, unique]`)

  Updates the current construction environment with the values extracted from the output of running external `command`, by passing it to a helper `function`. `command` may be a string or a list of strings representing the command and its arguments. If `function` is omitted or `None`, `env.MergeFlags` is used. By default, duplicate values are not added to any construction variables; you can specify `unique=False` to allow duplicate values to be added.

  `command` is executed using the SCons execution environment (that is, the construction variable `$ENV` in the current construction environment). If `command` needs additional information to operate properly, that needs to be set in the execution environment. For example, pkg-config may need a custom value set in the `PKG_CONFIG_PATH` environment variable.

  `env.MergeFlags` needs to understand the output produced by `command` in order to distribute it to appropriate construction variables. `env.MergeFlags` uses a separate function to do that processing - see `env.ParseFlags` for the details, including a table of options and corresponding construction variables. To provide alternative processing of the output of `command`, you can supply a custom `function`, which must accept three arguments: the construction environment to modify, a string argument containing the output from running `command`, and the optional `unique` flag.

`ParseDepends`(`filename, [must_exist, only_one]`), `env`.`ParseDepends`(`filename, [must_exist, only_one]`)

  Parses the contents of `filename` as a list of dependencies in the style of Make or mkdep, and explicitly establishes all of the listed dependencies.

  By default, it is not an error if `filename` does not exist. The optional `must_exist` argument may be set to `True` to have SCons raise an exception if the file does not exist, or is otherwise inaccessible.

  The optional `only_one` argument may be set to `True` to have SCons raise an exception if the file contains dependency information for more than one target. This can provide a small sanity check for files intended to be generated by, for example, the `gcc -M` flag, which should typically only write dependency information for one output file into a corresponding `.d` file.

  `filename` and all of the files listed therein will be interpreted relative to the directory of the `SConscript` file which calls the `ParseDepends` function.

`env`.`ParseFlags`(`flags, ...`)

  Parses one or more strings containing typical command-line flags for GCC-style tool chains and returns a dictionary with the flag values separated into the appropriate SCons construction variables. Intended as a companion to the `env.MergeFlags` method, but allows for the values in the returned dictionary to be modified, if necessary, before merging them into the construction environment. (Note that `env.MergeFlags` will call this method if its argument is not a dictionary, so it is usually not necessary to call `env.ParseFlags` directly unless you want to manipulate the values.)

  If the first character in any string is an exclamation mark (`!`), the rest of the string is executed as a command, and the output from the command is parsed as GCC tool chain command-line flags and added to the resulting dictionary. This can be used to call a `*-config` command typical of the POSIX programming environment (for example, pkg-config). Note that such a command is executed using the SCons execution environment; if the command needs additional information, that information needs to be explicitly provided. See `ParseConfig` for more details.

  Flag values are translated according to the prefix found, and added to the following construction variables:

      -arch                   CCFLAGS, LINKFLAGS
      -D                      CPPDEFINES
      -framework              FRAMEWORKS
      -frameworkdir=          FRAMEWORKPATH
      -fmerge-all-constants   CCFLAGS, LINKFLAGS
      -fopenmp                CCFLAGS, LINKFLAGS
      -fsanitize              CCFLAGS, LINKFLAGS
      -include                CCFLAGS
      -imacros                CCFLAGS
      -isysroot               CCFLAGS, LINKFLAGS
      -isystem                CCFLAGS
      -iquote                 CCFLAGS
      -idirafter              CCFLAGS
      -I                      CPPPATH
      -l                      LIBS
      -L                      LIBPATH
      -mno-cygwin             CCFLAGS, LINKFLAGS
      -mwindows               LINKFLAGS
      -openmp                 CCFLAGS, LINKFLAGS
      -pthread                CCFLAGS, LINKFLAGS
      -std=                   CFLAGS
      -stdlib=                CXXFLAGS
      -Wa,                    ASFLAGS, CCFLAGS
      -Wl,-rpath=             RPATH
      -Wl,-R,                 RPATH
      -Wl,-R                  RPATH
      -Wl,                    LINKFLAGS
      -Wp,                    CPPFLAGS
      -                       CCFLAGS
      +                       CCFLAGS, LINKFLAGS

  Any other strings not associated with options are assumed to be the names of libraries and added to the `$LIBS` construction variable.

  Examples (all of which produce the same result):

      dict = env.ParseFlags('-O2 -Dfoo -Dbar=1')
      dict = env.ParseFlags('-O2', '-Dfoo', '-Dbar=1')
      dict = env.ParseFlags(['-O2', '-Dfoo -Dbar=1'])
      dict = env.ParseFlags('-O2', '!echo -Dfoo -Dbar=1')

`Platform`(`plat`), `env`.`Platform`(`plat`)

  When called as a global function, returns a callable platform object selected by `plat` (defaults to the detected platform for the current system) that can be used to initialize a construction environment by passing it as the `platform` keyword argument to the `Environment` function.

  Example:

      env = Environment(platform=Platform('win32'))

  When called as a method of an environment, calls the platform object indicated by `plat` to update that environment.

      env.Platform('posix')

  See the manpage section "Construction Environments" for more details.

`Precious`(`target, ...`), `env`.`Precious`(`target, ...`)

  Marks `target` as precious so it is not deleted before it is rebuilt. Normally SCons deletes a target before building it. Multiple targets can be passed in a single call, and may be strings and/or nodes. Returns a list of the affected target nodes.

`env`.`Prepend`(`key=val, [...]`)

  Prepend values to construction variables in the current construction environment, works like `env.Append` (see for details), except that values are added to the front, rather than the end, of any existing value of the construction variable

  Example:

      env.Prepend(CCFLAGS='-g ', FOO=['foo.yyy'])

  See also `env.Append`, `env.AppendUnique` and `env.PrependUnique`.

`env`.`PrependENVPath`(`name, newpath, [envname, sep, delete_existing=True]`)

  Prepend directory paths from `newpath` to a search-path entry `name` in construction variable `envname` in the current enviromment (`env`). If `envname` is not given, the default is `"ENV"` (see `$ENV`). `envname` is expected to refer to a dictionary-like object; if it does not exist in `env` it will be created as an initially empty dict. `newpath` may be specified as a string, a directory node, or a list of strings. If a string, it may contain multiple paths separated by the system path separator (`os.pathsep`), or, if specified, by the value of `sep`. Top-relative path strings (starting with `#`) are recognized. The type of the existing value of `name` is preserved.

  Paths will only appear once. Duplicate paths in `newpath` are removed, preserving the first occurrence to maintain path order. If `delete_existing` is true (the default), existing duplicates are removed before prepending, otherwise, new duplicates are skipped. During comparisons, paths are normalized, to avoid issues with case differences (on case-insensitive filesystems) and with relative paths that may refer back to the same directory. The stored values are not modified by this process.

  Example:

      print('before:', env['ENV']['INCLUDE'])
      include_path = '/foo/bar:/foo'
      env.PrependENVPath('INCLUDE', include_path)
      print('after:', env['ENV']['INCLUDE'])

  Yields:

      before: /biz:/foo
      after: /foo/bar:/foo:/biz

  See also `env.AppendENVPath`.

`env`.`PrependUnique`(`key=val, [...], [delete_existing=False]`)

  Prepend values to construction variables in the current construction environment, maintaining uniqueness. Works like `env.Append`, except that values are added to the front, rather than the end, of the construction variable, and values that would become duplicates are not added. If `delete_existing` is set to a true value, then for any duplicate, the existing instance of `val` is first removed, then `val` is inserted, having the effect of moving it to the front.

  Example:

      env.PrependUnique(CCFLAGS='-g', FOO=['foo.yyy'])

  See also `env.Append`, `env.AppendUnique` and `env.Prepend`.

`Progress`(`callable, [interval]`), `Progress`(`string, [interval, file, overwrite]`), `Progress`(`list_of_strings, [interval, file, overwrite]`)

  Allows SCons to show progress made during the build by displaying a string or calling a function while evaluating Nodes (e.g. files).

  If the first specified argument is a Python callable (a function or an object that has a `__call__` method), the function will be called once every `interval` times a Node is evaluated (default `1`). The callable will be passed the evaluated Node as its only argument. (For future compatibility, it's a good idea to also add `*args` and `**kwargs` as arguments to your function or method signatures. This will prevent the code from breaking if SCons ever changes the interface to call the function with additional arguments in the future.)

  An example of a simple custom progress function that prints a string containing the Node name every 10 Nodes:

      def my_progress_function(node, *args, **kwargs):
          print('Evaluating node %s!' % node)
      Progress(my_progress_function, interval=10)

  A more complicated example of a custom progress display object that prints a string containing a count every 100 evaluated Nodes. Note the use of `\r` (a carriage return) at the end so that the string will overwrite itself on a display:

      import sys
      class ProgressCounter(object):
          count = 0
          def __call__(self, node, *args, **kw):
              self.count += 100
              sys.stderr.write('Evaluated %s nodes\r' % self.count)

      Progress(ProgressCounter(), interval=100)

  If the first argument to `Progress` is a string or list of strings, it is taken as text to be displayed every `interval` evaluated Nodes. If the first argument is a list of strings, then each string in the list will be displayed in rotating fashion every `interval` evaluated Nodes.

  The default is to print the string on standard output. An alternate output stream may be specified with the `file` keyword argument, which the caller must pass already opened.

  The following will print a series of dots on the error output, one dot for every 100 evaluated Nodes:

      import sys
      Progress('.', interval=100, file=sys.stderr)

  If the string contains the verbatim substring `$TARGET;`, it will be replaced with the Node. Note that, for performance reasons, this is not a regular SCons variable substitution, so you can not use other variables or use curly braces. The following example will print the name of every evaluated Node, using a carriage return) (`\r`) to cause each line to overwritten by the next line, and the `overwrite` keyword argument (default `False`) to make sure the previously-printed file name is overwritten with blank spaces:

      import sys
      Progress('$TARGET\r', overwrite=True)

  A list of strings can be used to implement a "spinner" on the user's screen as follows, changing every five evaluated Nodes:

      Progress(['-\r', '\\\r', '|\r', '/\r'], interval=5)

`Pseudo`(`target, ...`), `env`.`Pseudo`(`target, ...`)

  Marks `target` as a pseudo target, not representing the production of any physical target file. If any pseudo `target` does exist, SCons will abort the build with an error. Multiple targets can be passed in a single call, and may be strings and/or Nodes. Returns a list of the affected target nodes.

  `Pseudo` may be useful in conjuction with a builder call (such as `Command`) which does not create a physical target, and the behavior if the target accidentally existed would be incorrect. This is similar in concept to the GNU make `.PHONY` target. SCons also provides a powerful target alias capability (see `Alias`) which may provide more flexibility in many situations when defining target names that are not directly built.

`PyPackageDir`(`modulename`), `env`.`PyPackageDir`(`modulename`)

  Finds the location of `modulename`, which can be a string or a sequence of strings, each representing the name of a Python module. Construction variables are expanded in `modulename`. Returns a Directory Node (see `Dir`), or a list of Directory Nodes if `modulename` is a sequence. `None` is returned for any module not found.

  When a Tool module which is installed as a Python module is used, you need to specify a `toolpath` argument to `Tool`, `Environment` or `Clone`, as tools outside the standard project locations (`site_scons/site_tools`) will not be found otherwise. Using `PyPackageDir` allows this path to be discovered at runtime instead of hardcoding the path.

  Example:

      env = Environment(
          tools=["default", "ExampleTool"],
          toolpath=[PyPackageDir("example_tool")]
      )

`env`.`Replace`(`key=val, [...]`)

  Replaces construction variables in the Environment with the specified keyword arguments.

  Example:

      env.Replace(CCFLAGS='-g', FOO='foo.xxx')

`Repository`(`directory`), `env`.`Repository`(`directory`)

  Sets `directory` as a repository to be searched for files contributing to the build. Multiple calls to `Repository` are allowed, with repositories searched in the given order. Repositories specified via command-line option have higher priority.

  In scons, a repository is partial or complete copy of the source tree, from the top-level directory down, containing source files that can be used to build targets in the current worktree. Repositories can also contain derived files. An example might be an official source tree maintained by an integrator. If a repository contains derived files, they should be the result of building with SCons, so a signature database (sconsign) is present in the repository, allowing better decisions on whether they are up-to-date or not.

  Note that if an up-to-date derived file already exists in a repository, scons will not make a copy in the local directory tree. If you need a local copy to be made, use the `Local` method.

`Requires`(`target, prerequisite`), `env`.`Requires`(`target, prerequisite`)

  Specifies an order-only relationship between `target` and `prerequisite`. The prerequisites will be (re)built, if necessary, before the target file(s), but the target file(s) do not actually depend on the prerequisites and will not be rebuilt simply because the prerequisite file(s) change. `target` and `prerequisite` may each be a string or Node, or a list of strings or Nodes. If there are multiple `target` values, the prerequisite(s) are added to each one. Returns a list of the affected target nodes.

  Example:

      env.Requires('foo', 'file-that-must-be-built-before-foo')

`Return`(`[vars..., stop=True]`)

  Return to the calling SConscript, optionally returning the values of variables named in `vars`. Multiple strings containing variable names may be passed to `Return`. A string containing white space is split into individual variable names. Returns the value if one variable is specified, else returns a tuple of values. Returns an empty tuple if `vars` is omitted.

  By default `Return` stops processing the current SConscript and returns immediately. The optional `stop` keyword argument may be set to a false value to continue processing the rest of the SConscript file after the `Return` call (this was the default behavior prior to SCons 0.98.) However, the values returned are still the values of the variables in the named `vars` at the point `Return` was called.

  Examples:

      # Returns no values (evaluates False)
      Return()

      # Returns the value of the 'foo' Python variable.
      Return("foo")

      # Returns the values of the Python variables 'foo' and 'bar'.
      Return("foo", "bar")

      # Returns the values of Python variables 'val1' and 'val2'.
      Return('val1 val2')

`Scanner`(`function, [name, argument, skeys, path_function, node_class, node_factory, scan_check, recursive]`), `env`.`Scanner`(`function, [name, argument, skeys, path_function, node_class, node_factory, scan_check, recursive]`)

  Creates a Scanner object for the specified `function`. See manpage section "Scanner Objects" for a complete explanation of the arguments and behavior.

`SConscript`(`scriptnames, [exports, variant_dir, duplicate, must_exist]`), `env`.`SConscript`(`scriptnames, [exports, variant_dir, duplicate, must_exist]`), `SConscript`(`dirs=subdirs, [name=scriptname, exports, variant_dir, duplicate, must_exist]`), `env`.`SConscript`(`dirs=subdirs, [name=scriptname, exports, variant_dir, duplicate, must_exist]`)

  Executes subsidiary SConscript (build configuration) file(s). There are two ways to call the `SConscript` function.

  The first calling style is to supply one or more SConscript file names as the first positional argument, which can be a string or a list of strings. If there is a second positional argument, it is treated as if the `exports` keyword argument had been given (see below). Examples:

      SConscript('SConscript')  # run SConscript in the current directory
      SConscript('src/SConscript')  # run SConscript in the src directory
      SConscript(['src/SConscript', 'doc/SConscript'])
      SConscript(Split('src/SConscript doc/SConscript'))
      config = SConscript('MyConfig.py')

  The second calling style is to omit the positional argument naming the script and instead specify directory names using the `dirs` keyword argument. The value can be a string or list of strings. In this case, scons will execute a subsidiary configuration file named `SConscript` (by default) in each of the specified directories. You may specify a name other than `SConscript` by supplying an optional `name`=`scriptname` keyword argument. The first three examples below have the same effect as the first three examples above:

      SConscript(dirs='.')  # run SConscript in the current directory
      SConscript(dirs='src')  # run SConscript in the src directory
      SConscript(dirs=['src', 'doc'])
      SConscript(dirs=['sub1', 'sub2'], name='MySConscript')

  The optional `exports` keyword argument specifies variables to make available for use by the called SConscripts, which are evaluated in an isolated context and otherwise do not have access to local variables from the calling SConscript. The value may be a string or list of strings representing variable names, or a dictionary mapping local names to the names they can be imported by. For the first (scriptnames) calling style, a second positional argument will also be interpreted as `exports`; the second (directory) calling style accepts no positional arguments and must use the keyword form. These variables are locally exported only to the called SConscript file(s), and take precedence over any same-named variables in the global pool managed by the `Export` function. The subsidiary SConscript files must use the `Import` function to import the variables into their local scope. Examples:

      foo = SConscript('sub/SConscript', exports='env')
      SConscript('dir/SConscript', exports=['env', 'variable'])
      SConscript(dirs='subdir', exports='env variable')
      SConscript(dirs=['one', 'two', 'three'], exports='shared_info')

  If the optional `variant_dir` argument is present, it causes an effect equivalent to the `VariantDir` function, but in effect only within the scope of the `SConscript` call. The `variant_dir` argument is interpreted relative to the directory of the calling SConscript file. The source directory is the directory in which the called SConscript file resides and the SConscript file is evaluated as if it were in the `variant_dir` directory. Thus:

      SConscript('src/SConscript', variant_dir='build')

  is equivalent to:

      VariantDir('build', 'src')
      SConscript('build/SConscript')

  If the sources are in the same directory as the `SConstruct`,

      SConscript('SConscript', variant_dir='build')

  is equivalent to:

      VariantDir('build', '.')
      SConscript('build/SConscript')

  The optional `duplicate` argument is interpreted as for `VariantDir`. If the `variant_dir` argument is omitted, the `duplicate` argument is ignored. See the description of `VariantDir` for additional details and restrictions.

  If the optional `must_exist` is `True` (the default), an exception is raised if a requested SConscript file is not found. To allow missing scripts to be silently ignored (the default behavior prior to SCons version 3.1), pass `must_exist=False` in the `SConscript` call.

  Changed in 4.6.0: `must_exist` now defaults to `True`.

  Here are some composite examples:

      # collect the configuration information and use it to build src and doc
      shared_info = SConscript('MyConfig.py')
      SConscript('src/SConscript', exports='shared_info')
      SConscript('doc/SConscript', exports='shared_info')

      # build debugging and production versions.  SConscript
      # can use Dir('.').path to determine variant.
      SConscript('SConscript', variant_dir='debug', duplicate=0)
      SConscript('SConscript', variant_dir='prod', duplicate=0)

      # build debugging and production versions.  SConscript
      # is passed flags to use.
      opts = { 'CPPDEFINES' : ['DEBUG'], 'CCFLAGS' : '-pgdb' }
      SConscript('SConscript', variant_dir='debug', duplicate=0, exports=opts)
      opts = { 'CPPDEFINES' : ['NODEBUG'], 'CCFLAGS' : '-O' }
      SConscript('SConscript', variant_dir='prod', duplicate=0, exports=opts)

      # build common documentation and compile for different architectures
      SConscript('doc/SConscript', variant_dir='build/doc', duplicate=0)
      SConscript('src/SConscript', variant_dir='build/x86', duplicate=0)
      SConscript('src/SConscript', variant_dir='build/ppc', duplicate=0)

  `SConscript` returns the values of any variables named by the executed SConscript file(s) in arguments to the `Return` function. If a single `SConscript` call causes multiple scripts to be executed, the return value is a tuple containing the returns of each of the scripts. If an executed script does not explicitly call `Return`, it returns `None`.

`SConscriptChdir`(`value`)

  By default, scons changes its working directory to the directory in which each subsidiary SConscript file lives while reading and processing that script. This behavior may be disabled by specifying an argument which evaluates false, in which case scons will stay in the top-level directory while reading all SConscript files. (This may be necessary when building from repositories, when all the directories in which SConscript files may be found don't necessarily exist locally.) You may enable and disable this ability by calling `SConscriptChdir` multiple times.

  Example:

      SConscriptChdir(False)
      SConscript('foo/SConscript')	# will not chdir to foo
      SConscriptChdir(True)
      SConscript('bar/SConscript')	# will chdir to bar

`SConsignFile`(`[name, dbm_module]`), `env`.`SConsignFile`(`[name, dbm_module]`)

  Specify where to store the SCons file signature database, and which database format to use. This may be useful to specify alternate database files and/or file locations for different types of builds.

  The optional `name` argument is the base name of the database file(s). If not an absolute path name, these are placed relative to the directory containing the top-level `SConstruct` file. The default is `.sconsign`. The actual database file(s) stored on disk may have an appropriate suffix appended by the chosen `dbm_module`

  The optional `dbm_module` argument specifies which Python database module to use for reading/writing the file. The module must be imported first; then the imported module name is passed as the argument. The default is a custom `SCons.dblite` module that uses pickled Python data structures, which works on all Python versions. See documentation of the Python `dbm` module for other available types.

  If called with no arguments, the database will default to `.sconsign.dblite` in the top directory of the project, which is also the default if if `SConsignFile` is not called.

  The setting is global, so the only difference between the global function and the environment method form is variable expansion on `name`. There should only be one active call to this function/method in a given build setup.

  If `name` is set to `None`, scons will store file signatures in a separate `.sconsign` file in each directory, not in a single combined database file. This is a backwards-compatibility measure to support what was the default behavior prior to SCons 0.97 (i.e. before 2008). Use of this mode is discouraged and may be deprecated in a future SCons release.

  Examples:

      # Explicitly stores signatures in ".sconsign.dblite"
      # in the top-level SConstruct directory (the default behavior).
      SConsignFile()

      # Stores signatures in the file "etc/scons-signatures"
      # relative to the top-level SConstruct directory.
      # SCons will add a database suffix to this name.
      SConsignFile("etc/scons-signatures")

      # Stores signatures in the specified absolute file name.
      # SCons will add a database suffix to this name.
      SConsignFile("/home/me/SCons/signatures")

      # Stores signatures in a separate .sconsign file
      # in each directory.
      SConsignFile(None)

      # Stores signatures in a GNU dbm format .sconsign file
      import dbm.gnu
      SConsignFile(dbm_module=dbm.gnu)

`env`.`SetDefault`(`key=val, [...]`)

  Sets construction variables to default values specified with the keyword arguments if (and only if) the variables are not already set. The following statements are equivalent:

      env.SetDefault(FOO='foo')
      if 'FOO' not in env:
          env['FOO'] = 'foo'

`SetOption`(`name, value`), `env`.`SetOption`(`name, value`)

  Set option variable `name` to `value`. Settable options have corresponding command-line arguments, which can be used for one-time overrides, as a value set via command-line option will take precedence over one set with `SetOption`. The table shows the correspondence between the option name and the command-line argument(s). `SetOption` calls can also be placed in a `site_init.py` file.

  The behavior of the options is described in the manpage entry for the command-line version. The `value` parameter is mandatory; for option values which are boolean in nature (that is, the command line option does not take an argument) use a `value` which evaluates to true (e.g. `True`, `1`) or false (e.g. `False`, `0`).

  Options which affect the reading and processing of SConscript files are not settable using `SetOption` since those files must be read in order to find the `SetOption` call in the first place.

  For project-specific options (sometimes called local options) added via an `AddOption` call, `SetOption` is available only after the `AddOption` call has completed successfully, and only if that call included the `settable=True` keyword argument.

  The settable variables with their associated command-line options are:

  Settable name | Command-line argument | Notes
  --- | --- | ---
  `clean` | `-c`, `--clean`, `--remove` |
  `diskcheck` | `--diskcheck` |
  `duplicate` | `--duplicate` |
  `experimental` | `--experimental` | Since 4.2.
  `hash_chunksize` | `--hash-chunksize` | Replaces `md5_chunksize`. Since 4.2
  `hash_format` | `--hash-format` | Since 4.2
  `help` | `-h`, `--help` |
  `implicit_cache` | `--implicit-cache` |
  `implicit_deps_changed` | `--implicit-deps-changed` | Also sets `implicit_cache`. Settable since 4.2
  `implicit_deps_unchanged` | `--implicit-deps-unchanged` | Also sets `implicit_cache`. Settable since 4.2
  `max_drift` | `--max-drift` |
  `md5_chunksize` | `--hash-chunksize` | Synonym for `hash_chunksize`. Deprecated since 4.2
  `no_exec` | `-n`, `--no-exec`, `--just-print`, `--dry-run`, `--recon` |
  `no_progress` | `-Q` | See [a]
  `num_jobs` | `-j`, `--jobs` |
  `random` | `--random` |
  `silent` | `-s`, `--silent`, `--quiet` |
  `stack_size` | `--stack-size` |
  `warn` | `--warn` |
  [a] If `no_progress` is set via `SetOption` in an SConscript file (but not if set in a `site_init.py` file) there will still be an initial status message about reading SConscript files since SCons has to start reading them before it can see the `SetOption`.

  Example:

      SetOption('max_drift', 0)

`SideEffect`(`side_effect, target`), `env`.`SideEffect`(`side_effect, target`)

  Declares `side_effect` as a side effect of building `target`. Both `side_effect` and `target` can be a list, a file name, or a node. A side effect is a target file that is created or updated as a side effect of building other targets. For example, a Windows PDB file is created as a side effect of building the .obj files for a static library, and various log files are created updated as side effects of various TeX commands. If a target is a side effect of multiple build commands, scons will ensure that only one set of commands is executed at a time. Consequently, you only need to use this method for side-effect targets that are built as a result of multiple build commands.

  Because multiple build commands may update the same side effect file, by default the `side_effect` target is not automatically removed when the `target` is removed by the `-c` option. (Note, however, that the `side_effect` might be removed as part of cleaning the directory in which it lives.) If you want to make sure the `side_effect` is cleaned whenever a specific `target` is cleaned, you must specify this explicitly with the `Clean` or `env.Clean` function.

  This function returns the list of side effect Node objects that were successfully added. If the list of side effects contained any side effects that had already been added, they are not added and included in the returned list.

`Split`(`arg`), `env`.`Split`(`arg`)

  If `arg` is a string, splits on whitespace and returns a list of strings without whitespace. This mode is the most common case, and can be used to split a list of filenames (for example) rather than having to type them as a list of individually quoted words. If `arg` is a list or tuple returns the list or tuple unchanged. If `arg` is any other type of object, returns a list containing just the object. These non-string cases do not actually do any spliting, but allow an argument variable to be passed to `Split` without having to first check its type.

  Example:

      files = Split("f1.c f2.c f3.c")
      files = env.Split("f4.c f5.c f6.c")
      files = Split("""
          f7.c
          f8.c
          f9.c
      """)

`env`.`subst`(`input, [raw, target, source, conv]`)

  Performs construction variable interpolation (substitution) on `input`, which can be a string or a sequence. Substitutable elements take the form `${`expression`}`, although if there is no ambiguity in recognizing the element, the braces can be omitted. A literal $ can be entered by using $$.

  By default, leading or trailing white space will be removed from the result, and all sequences of white space will be compressed to a single space character. Additionally, any `$(` and `$)` character sequences will be stripped from the returned string, The optional `raw` argument may be set to `1` if you want to preserve white space and `$(`-`$)` sequences. The `raw` argument may be set to `2` if you want to additionally discard all characters between any `$(` and `$)` pairs (as is done for signature calculation).

  If `input` is a sequence (list or tuple), the individual elements of the sequence will be expanded, and the results will be returned as a list.

  The optional `target` and `source` keyword arguments must be set to lists of target and source nodes, respectively, if you want the `$TARGET`, `$TARGETS`, `$SOURCE` and `$SOURCES` to be available for expansion. This is usually necessary if you are calling `env.subst` from within a Python function used as an SCons action.

  Returned string values or sequence elements are converted to their string representation by default. The optional `conv` argument may specify a conversion function that will be used in place of the default. For example, if you want Python objects (including SCons Nodes) to be returned as Python objects, you can use a Python lambda expression to pass in an unnamed function that simply returns its unconverted argument.

  Example:

      print(env.subst("The C compiler is: $CC"))

      def compile(target, source, env):
          sourceDir = env.subst(
              "${SOURCE.srcdir}",
              target=target,
              source=source
          )

      source_nodes = env.subst('$EXPAND_TO_NODELIST', conv=lambda x: x)

`Tag`(`node, tags`)

  Annotates file or directory Nodes with information about how the `Package` Builder should package those files or directories. All Node-level tags are optional.

  Examples:

      # makes sure the built library will be installed with 644 file access mode
      Tag(Library('lib.c'), UNIX_ATTR="0o644")

      # marks file2.txt to be a documentation file
      Tag('file2.txt', DOC)

`Tool`(`name, [toolpath, key=value, ...]`), `env`.`Tool`(`name, [toolpath, key=value, ...]`)

  Locates the tool specification module `name` and returns a callable tool object for that tool. When the environment method (`env.Tool`) form is used, the tool object is automatically called before the method returns to update `env`, and `name` is appended to the `$TOOLS` construction variable in that environment. When the global function `Tool` form is used, the tool object is constructed but not called, as it lacks the context of an environment to update, and the returned object needs to be used to arrange for the call.

  The tool module is searched for in the tool search paths (see the Tools section in the manual page for details) and in any paths specified by the optional `toolpath` parameter, which must be a list of strings. If `toolpath` is omitted, the `toolpath` supplied when the environment was created, if any, is used.

  Any remaining keyword arguments are saved in the tool object, and will be passed to the tool module's `generate` function when the tool object is actually called. The `generate` function can update the construction environment with construction variables and arrange any other initialization needed to use the mechanisms that tool describes, and can use these extra arguments to help guide its actions.

  Changed in version 4.2: `env.Tool` now returns the tool object, previously it did not return (i.e. returned `None`).

  Examples:

      env.Tool('gcc')
      env.Tool('opengl', toolpath=['build/tools'])

  The returned tool object can be passed to an `Environment` or `Clone` call as part of the `tools` keyword argument, in which case the tool is applied to the environment being constructed, or it can be called directly, in which case a construction environment to update must be passed as the argument. Either approach will also update the `$TOOLS` construction variable.

  Examples:

      env = Environment(tools=[Tool('msvc')])

      env = Environment()
      msvctool = Tool('msvc')
      msvctool(env)  # adds 'msvc' to the TOOLS variable
      gltool = Tool('opengl', toolpath = ['tools'])
      gltool(env)  # adds 'opengl' to the TOOLS variable

`ValidateOptions`(`[throw_exception=False]`)

  Check that all the options specified on the command line are either SCons built-in options or defined via calls to `AddOption`. SCons will eventually fail on unknown options anyway, but calling this function allows the build to "fail fast" before executing expensive logic later in the build.

  This function should only be called after the last `AddOption` call in your `SConscript` logic. Be aware that some tools call `AddOption`, if you are getting error messages for arguments that they add, you will need to ensure that those tools are loaded before calling `ValidateOptions`.

  If there are any unknown command line options, `ValidateOptions` prints an error message and exits with an error exit status. If the optional `throw_exception` argument is `True` (default is `False`), a `SConsBadOptionError` is raised, giving an opportunity for the `SConscript` logic to catch that exception and handle invalid options appropriately. Note that this exception name needs to be imported (see the example below).

  A common build problem is typos (or thinkos) - a user enters an option that is just a little off the expected value, or perhaps a different word with a similar meaning. It may be useful to abort the build before going too far down the wrong path. For example:

      $ scons --compilers=mingw  # the correct flag is --compiler

  Here SCons could go off and run a bunch of configure steps with the default value of `--compiler`, since the incorrect command line did not actually supply a value to it, costing developer time to track down why the configure logic made the "wrong" choices. This example shows catching this:

      from SCons.Script.SConsOptions import SConsBadOptionError

      AddOption(
          '--compiler',
          dest='compiler',
          action='store',
          default='gcc',
          type='string',
      )

      # ... other SConscript logic ...

      try:
          ValidateOptions(throw_exception=True)
      except SConsBadOptionError as e:
          print(f"ValidateOptions detects a fail: ", e.opt_str)
          Exit(3)

  New in version 4.5.0

`Value`(`value, [built_value], [name]`), `env`.`Value`(`value, [built_value], [name]`)

  Returns a Node object representing the specified Python `value`. Value Nodes can be used as dependencies of targets. If the string representation of the Value Node changes between SCons runs, it is considered out-of-date and any targets depending on it will be rebuilt. Since Value Nodes have no filesystem representation, timestamps are not used; the timestamp deciders perform the same content-based up to date check.

  The optional `built_value` argument can be specified when the Value Node is created to indicate the Node should already be considered "built."

  The optional `name` parameter can be provided as an alternative name for the resulting `Value` node; this is advised if the `value` parameter cannot be converted to a string.

  Value Nodes have a `write` method that can be used to "build" a Value Node by setting a new value. The corresponding `read` method returns the built value of the Node.

  Changed in version 4.0: the `name` parameter was added.

  Examples:

      env = Environment()

      def create(target, source, env):
          """Action function to create a file from a Value.

          Writes 'prefix=$SOURCE' into the file name given as $TARGET.
          """
          with open(target[0], 'wb') as f:
              f.write(b'prefix=' + source[0].get_contents() + b'\n')

      # Fetch the prefix= argument, if any, from the command line.
      # Use /usr/local as the default.
      prefix = ARGUMENTS.get('prefix', '/usr/local')

      # Attach builder named Config to the construction environment
      # using the 'create' action function above.
      env['BUILDERS']['Config'] = Builder(action=create)
      env.Config(target='package-config', source=Value(prefix))

      def build_value(target, source, env):
          """Action function to "build" a Value.

          Writes contents of $SOURCE into $TARGET, thus updating if it existed.
          """
          target[0].write(source[0].get_contents())

      output = env.Value('before')
      input = env.Value('after')

      # Attach a builder named UpdateValue to the construction environment
      # using the 'build_value' action function above.
      env['BUILDERS']['UpdateValue'] = Builder(action=build_value)
      env.UpdateValue(target=Value(output), source=Value(input))

`VariantDir`(`variant_dir, src_dir, [duplicate]`), `env`.`VariantDir`(`variant_dir, src_dir, [duplicate]`)

  Sets up a mapping to define a variant build directory in `variant_dir`. `src_dir` must not be underneath `variant_dir`. A `VariantDir` mapping is global, even if called using the `env.VariantDir` form. `VariantDir` can be called multiple times with the same `src_dir` to set up multiple variant builds with different options.

  Note if `variant_dir` is not under the project top directory, target selection rules will not pick targets in the variant directory unless they are explicitly specified.

  When files in `variant_dir` are referenced, SCons backfills as needed with files from `src_dir` to create a complete build directory. By default, SCons physically duplicates the source files, SConscript files, and directory structure as needed into the variant directory. Thus, a build performed in the variant directory is guaranteed to be identical to a build performed in the source directory even if intermediate source files are generated during the build, or if preprocessors or other scanners search for included files using paths relative to the source file, or if individual compilers or other invoked tools are hard-coded to put derived files in the same directory as source files. Only the files SCons calculates are needed for the build are duplicated into `variant_dir`. If possible on the platform, the duplication is performed by linking rather than copying. This behavior is affected by the `--duplicate` command-line option.

  Duplicating the source files may be disabled by setting the `duplicate` argument to `False`. This will cause SCons to invoke Builders using the path names of source files in `src_dir` and the path names of derived files within `variant_dir`. This is more efficient than duplicating, and is safe for most builds; revert to `duplicate=True` if it causes problems.

  `VariantDir` works most naturally when used with a subsidiary SConscript file. The subsidiary SConscript file must be called as if it were in `variant_dir`, regardless of the value of `duplicate`. When calling an SConscript file, you can use the `exports` keyword argument to pass parameters (individually or as an appropriately set up environment) so the SConscript can pick up the right settings for that variant build. The SConscript must `Import` these to use them. Example:

      env1 = Environment(...settings for variant1...)
      env2 = Environment(...settings for variant2...)

      # run src/SConscript in two variant directories
      VariantDir('build/variant1', 'src')
      SConscript('build/variant1/SConscript', exports={"env": env1})
      VariantDir('build/variant2', 'src')
      SConscript('build/variant2/SConscript', exports={"env": env2})

  See also the `SConscript` function for another way to specify a variant directory in conjunction with calling a subsidiary SConscript file.

  More examples:

      # use names in the build directory, not the source directory
      VariantDir('build', 'src', duplicate=0)
      Program('build/prog', 'build/source.c')

      # this builds both the source and docs in a separate subtree
      VariantDir('build', '.', duplicate=0)
      SConscript(dirs=['build/src','build/doc'])

      # same as previous example, but only uses SConscript
      SConscript(dirs='src', variant_dir='build/src', duplicate=0)
      SConscript(dirs='doc', variant_dir='build/doc', duplicate=0)

`Virtualenv`()

  If the SCons process is running inside a Python virtual environment, return the path to the directory where that environment is stored, else an empty string. The result can be treated as a boolean value if the path is unneeded.

`WhereIs`(`program, [path, pathext, reject]`), `env`.`WhereIs`(`program, [path, pathext, reject]`)

  Searches for the specified executable `program`, returning the full path to the program or `None`.

  When called as a construction environment method, searches the paths in the `path` keyword argument, or if `None` (the default) the paths listed in the construction environment (`env``['ENV']['PATH']`). The external environment's path list (`os.environ['PATH']`) is used as a fallback if the key `env``['ENV']['PATH']` does not exist.

  On Windows systems, searches for executable programs with any of the file extensions listed in the `pathext` keyword argument, or if `None` (the default) the pathname extensions listed in the construction environment (`env``['ENV']['PATHEXT']`). The external environment's pathname extensions list (`os.environ['PATHEXT']`) is used as a fallback if the key `env``['ENV']['PATHEXT']` does not exist.

  When called as a global function, uses the external environment's path `os.environ['PATH']` and path extensions `os.environ['PATHEXT']`, respectively, if `path` and `pathext` are `None`.

  Will not select any path name or names in the optional `reject` list.

Prev |  | Next
Appendix C. Tools | Home | Appendix E. Handling Common Tasks