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
env
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
(arguments
)
Adds a local (project-specific) command-line option.
arguments
are the same as those supported by the add_option
method in the standard Python library module optparse
,
with a few additional capabilities noted below.
See the documentation for
optparse
for a thorough discussion of its option-processing capabities.
In addition to the arguments and values supported by the
optparse
add_option
method, AddOption
allows setting the
nargs
keyword value to
a string consisting of a question mark
('?'
)
to indicate that the option argument for
that option string is optional.
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
.
SetOption
is not currently supported for
options added with AddOption
.
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.
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
)
Arranges for the specified
action
to be performed
after the specified
target
has been built.
The specified action(s) 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.
AddPreAction
(target, action
), env
.AddPreAction
(target, action
)
Arranges for the specified
action
to be performed
before the specified
target
is built.
The specified action(s) 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 "final" action that specifically
generates the specified target(s).
For example, when building an executable program
from a specified source
.c
file via an intermediate object file:
foo = Program('foo.c') AddPreAction(foo, 'pre_action')
The specified
pre_action
would be executed before
scons
calls the link command that actually
generates the executable program binary
foo
,
not before compiling the
foo.c
file into an object file.
Alias
(alias, [targets, [action]]
), env
.Alias
(alias, [targets, [action]]
)
Creates one or more phony targets that
expand to one or more other targets.
An optional
action
(command)
or list of actions
can be specified that will be executed
whenever the any of the alias targets are out-of-date.
Returns the Node object representing the alias,
which exists outside of any file system.
This Node object, or the alias name,
may be used as a dependency of any other target,
including another alias.
Alias
can be called multiple times for the same
alias to add additional targets to the alias,
or additional actions to the list for this alias.
Aliases are global even if set through
the construction environment method.
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 allowed
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 allowed exceptions.
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 evalute 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, [...]
)
Intelligently append values to construction variables in the construction environment
named by 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 normally having to know the data type of an existing construction variable.
Regular Python syntax can also be used to manipulate the construction variable,
but for that you must know the type of the construction variable:
for example, different Python syntax is needed to combine
a list of values with a single string value, or vice versa.
Some pre-defined construction variables do have type expectations
based on how SCons will use them,
for example $CPPDEFINES
is normally a string or a list of strings,
but can be a string,
a list of strings,
a list of tuples,
or a dictionary, while $LIBEMITTER
would expect a callable or list of callables,
and $BUILDERS
would expect a mapping type.
Consult the documentation for the various construction variables for more details.
The following descriptions apply to both the append and prepend functions, the only difference being the insertion point of the added values.
If env
. does not have a construction variable
indicated by key
,
val
is added to the environment under that key as-is.
val
can be almost any type,
and SCons will combine it with an existing value into an appropriate type,
but there are a few special cases to be aware of.
When two strings are combined,
the result is normally a new string,
with the caller responsible for supplying any needed separation.
The exception to this is the construction variable $CPPDEFINES
,
in which each item will be postprocessed by adding a prefix
and/or suffix,
so the contents are treated as a list of strings, that is,
adding a string will result in a separate string entry,
not a combined string. For $CPPDEFINES
as well as
for $LIBS
, and the various *PATH
;
variables, SCons will supply the compiler-specific
syntax (e.g. adding a -D
or /D
prefix for $CPPDEFINES
), so this syntax should be omitted when
adding values to these variables.
Example (gcc syntax shown in the expansion of CPPDEFINES
):
env = Environment(CXXFLAGS="-std=c11", CPPDEFINES="RELEASE") print("CXXFLAGS={}, CPPDEFINES={}".format(env['CXXFLAGS'], env['CPPDEFINES'])) # notice including a leading space in CXXFLAGS value env.Append(CXXFLAGS=" -O", CPPDEFINES="EXTRA") print("CXXFLAGS={}, CPPDEFINES={}".format(env['CXXFLAGS'], env['CPPDEFINES'])) print("CPPDEFINES will expand to {}".format(env.subst("$_CPPDEFFLAGS")))
$ scons -Q CXXFLAGS=-std=c11, CPPDEFINES=RELEASE CXXFLAGS=-std=c11 -O, CPPDEFINES=['RELEASE', 'EXTRA'] CPPDEFINES will expand to -DRELEASE -DEXTRA scons: `.' is up to date.
Because $CPPDEFINES
is intended to
describe C/C++ pre-processor macro definitions,
it accepts additional syntax.
Preprocessor macros can be valued, or un-valued, as in
-DBAR=1
or
-DFOO
.
The macro can be be supplied as a complete string including the value,
or as a tuple (or list) of macro, value, or as a dictionary.
Example (again gcc syntax in the expanded defines):
env = Environment(CPPDEFINES="FOO") print("CPPDEFINES={}".format(env['CPPDEFINES'])) env.Append(CPPDEFINES="BAR=1") print("CPPDEFINES={}".format(env['CPPDEFINES'])) env.Append(CPPDEFINES=("OTHER", 2)) print("CPPDEFINES={}".format(env['CPPDEFINES'])) env.Append(CPPDEFINES={"EXTRA": "arg"}) print("CPPDEFINES={}".format(env['CPPDEFINES'])) print("CPPDEFINES will expand to {}".format(env.subst("$_CPPDEFFLAGS")))
$ scons -Q CPPDEFINES=FOO CPPDEFINES=['FOO', 'BAR=1'] CPPDEFINES=['FOO', 'BAR=1', ('OTHER', 2)] CPPDEFINES=['FOO', 'BAR=1', ('OTHER', 2), {'EXTRA': 'arg'}] CPPDEFINES will expand to -DFOO -DBAR=1 -DOTHER=2 -DEXTRA=arg scons: `.' is up to date.
Adding a string val
to a dictonary construction variable will enter
val
as the key in the dict,
and None
as its value.
Using a tuple type to supply a key + value 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 a Python exception will be raised.
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 there is only a single string to add.
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 path elements specified by newpath
to the given search path string or list name
in mapping envname
in the construction environment.
Supplying envname
is optional:
the default is the execution environment $ENV
.
Optional sep
is used as the search path separator,
the default is the platform's separator (os.pathsep
).
A path element will only appear once.
Any duplicates in newpath
are dropped,
keeping the last appearing (to preserve path order).
If delete_existing
is False
(the default)
any addition duplicating an existing path element is ignored;
if delete_existing
is True
the existing value will
be dropped and the path element will be added at the end.
To help maintain uniqueness all paths are normalized (using
os.path.normpath
and
os.path.normcase
).
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
(see for details),
except that values already present in the construction variable
will not be added again.
If delete_existing
is True
,
the existing matching value is first removed,
and the requested value is added,
having the effect of moving such values 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.
When specifying a
custom_class
which should be a class type which is a subclass of
SCons.CacheDir.CacheDir
, SCons will
internally invoke this class to use for performing caching operations.
This argument is optional and if left to default None
, will use the
default SCons.CacheDir.CacheDir
class.
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
.
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 so 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
will print the action that would
have been used to build the file without
considering cache retrieval.
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
.
If the
--cache-force
option is used,
scons
will place a copy of
all
derived files in 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, etc. if needed.
Clean
(targets, files_or_dirs
), env
.Clean
(targets, files_or_dirs
)
This specifies a list of files or directories which should be removed
whenever the targets are specified with the
-c
command line option.
The specified targets may be a list
or an individual target.
Multiple calls to
Clean
are legal,
and create new targets or add files and directories to the
clean list for the specified targets.
Multiple files or directories should be specified
either as separate arguments to the
Clean
method, or as a list.
Clean
will also accept the return value of any of the construction environment
Builder methods.
Examples:
The related
NoClean
function overrides calling
Clean
for the same target,
and any targets passed to both functions will
not
be removed by the
-c
option.
Examples:
Clean('foo', ['bar', 'baz']) Clean('dist', env.Program('hello', 'hello.c')) Clean(['foo', 'bar'], 'something_else_to_clean')
In this example, installing the project creates a subdirectory for the documentation. This statement causes the subdirectory to be removed if the project is deinstalled.
Clean(docdir, os.path.join(docdir, projectname))
env
.Clone
([key=val, ...]
)Returns a separate copy of a construction environment. If there are any keyword arguments specified, they are added to the returned copy, overwriting any existing values for the keywords.
Example:
env2 = env.Clone() env3 = env.Clone(CCFLAGS='-g')
Additionally, 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')
Command
(target, source, action, [key=val, ...]
), env
.Command
(target, source, action, [key=val, ...]
)
Executes a specific action
(or list of actions)
to build a target
file or files
from a source
file or files.
This is more convenient
than defining a separate Builder object
for a single special-case build.
The
Command
function accepts
source_scanner
,
target_scanner
,
source_factory
, and
target_factory
keyword arguments. These arguments can
be used to specify
a Scanner object
that will be used to apply a custom
scanner for a source or target.
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 of function calls.
The *_factory
arguments take a factory function that
Command
will use to turn any sources or targets
specified as strings into SCons Nodes.
See the manpage section "Builder Objects"
for more information about how these
arguments work in a Builder.
Any other keyword arguments specified override any same-named existing construction variables.
An 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', str(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.
Decider
(function
), env
.Decider
(function
)
Specifies that all up-to-date decisions for
targets built through this construction environment
will be handled by the specified
function
.
function
can be the name of
a function or one of the following strings
that specify the predefined decision function
that will be applied:
"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.
"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 be performing an checksum
on the dependency's contents
and comparing it to the checksum recorded the
last time the target was built.
MD5
can be used as a synonym for
content
, but it 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.
MD5-timestamp
can be used as a synonym for
content-timestamp
, but it is deprecated.
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 tme
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 appopriate.
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
([**kwargs]
)
Instantiates and returns the default construction environment object.
The default environment is used internally by SCons
in order to execute many of the global functions in this list
(that is, those not called as methods of a specific construction environment).
It is not mandatory to call DefaultEnvironment
:
the default environment will be instantiated automatically when the
build phase begins if the function has not been called,
however calling it explicitly gives the opportunity to
affect and examine the contents of the default environment.
The default environment is a singleton, so the keyword
arguments affect it only on the first call, on subsequent
calls the already-constructed object is returned and
any keyword arguments are silently ignored.
The default environment can be modified after instantiation
in the same way as any construction environment.
Modifying the default environment has no effect on the construction environment
constructed by an Environment
or Clone
call.
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
([vars]
)Returns a dictionary object containing the construction variables in the construction environment. If there are any arguments specified, the values of the specified construction variables are returned as a string (if one argument) or as a list of strings.
Example:
cvars = env.Dictionary() cc_values = env.Dictionary('CC', 'CCFLAGS', 'CCCOM')
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 "File and Directory Nodes" for more information.
env
.Dump
([key], [format]
)
Serializes construction variables to a string.
The method supports the following formats specified by
format
:
pretty
Returns a pretty printed representation of the environment (if
format
is not specified, this is the default).
json
Returns a JSON-formatted string representation of the environment.
If key
is
None
(the default) the entire
dictionary of construction variables is serialized.
If supplied, it is taken as the name of a construction variable
whose value is serialized.
This SConstruct:
env=Environment() print(env.Dump('CCCOM'))
will print:
'$CC -c -o $TARGET $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS $SOURCES'
While this SConstruct:
env = Environment() print(env.Dump())
will print:
{ '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
), env
.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]
), env
.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 also specially recognized.
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]
), env
.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 from the current
SConscript file to a global collection where they can be
imported by other SConscript files.
vars
may be one or more
strings representing variable names to be exported.
If a string contains whitespace, it is split into
separate strings, as if multiple string arguments
had been given. A vars
argument
may also be a dictionary, which can be used to map variables
to different names when exported.
Keyword arguments can be used to provide names and their values.
Export
calls are cumulative. Specifying a previously
exported variable will overwrite the earlier value.
Both local variables and global variables can be exported.
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 supports an exports
argument that allows exporting a variable or
set of variables to a specific SConscript file or files.
See the description below.
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 "File and Directory 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
(), env
.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
)
This function provides a way to query the value of
options which can be set via the command line or using the
SetOption
function.
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 the addition
happens prior to the GetOption
call in the SConscript files.
Query name | Command-line options | 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_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 ,
--md5-chunksize
| --hash-chunksize 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 |
See the documentation for the corresponding command line option for information about each specific option.
Glob
(pattern, [ondisk, source, strings, exclude]
), env
.Glob
(pattern, [ondisk, source, strings, exclude]
)
Returns Nodes (or strings) that match the specified
pattern
,
relative to the directory of the current
SConscript
file.
The evironment method form (env.Glob
)
performs string substition on
pattern
and returns whatever matches
the resulting expanded pattern.
The specified
pattern
uses Unix shell style metacharacters for matching:
* matches everything ? matches any single character [seq] matches any character in seq [!seq] matches any char not in seq
If the first character of a filename is a dot, it must be matched explicitly. Character matches do not span directory separators.
The
Glob
knows about
repositories
(see the
Repository
function)
and source directories
(see the
VariantDir
function)
and
returns a Node (or string, if so configured)
in the local (SConscript) directory
if a matching Node is found
anywhere in a corresponding
repository or source directory.
The
ondisk
argument may be set to a value which evaluates
False
to disable the search for matches on disk,
thereby only returning matches among
already-configured File or Dir Nodes.
The default behavior is to
return corresponding Nodes
for any on-disk matches found.
The
source
argument may be set to a value which evaluates
True
to specify that,
when the local directory is a
VariantDir
,
the returned Nodes should be from the
corresponding source directory,
not the local directory.
The
strings
argument may be set to a value which evaluates
True
to have the
Glob
function return strings, not Nodes,
that represent the matched files or directories.
The returned strings will be relative to
the local (SConscript) directory.
(Note that This may make it easier to perform
arbitrary manipulation of file names,
but if the returned strings are
passed to a different
SConscript
file,
any Node translation will be relative
to the other
SConscript
directory,
not the original
SConscript
directory.)
The
exclude
argument may be set to a pattern or a list of patterns
(following the same Unix shell semantics)
which must be filtered out of returned elements.
Elements matching a least one pattern of
this list will be excluded.
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
), env
.Help
(text, append=False
)
Specifies a local help message to be printed if the
-h
argument is given to
scons.
Subsequent calls to
Help
append text
to the previously
defined local help text.
For the first call to Help
only,
if append
is False
(the default)
any local help message generated through
AddOption
calls is replaced.
If append
is True
,
text
is appended to
the existing help text.
Ignore
(target, dependency
), env
.Ignore
(target, dependency
)The specified dependency file(s) will be ignored when deciding if the target file(s) need to be rebuilt.
You can also use
Ignore
to remove a target from the default build.
In order to do this you must specify the directory the target will
be built in as the target, and the file you want to skip building
as the dependency.
Note that this will only remove the dependencies listed from the files built by default. It will still be built if that dependency is needed by another object being built. 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 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
SConscript
.
Variables exported by
SConscript
take precedence.
Multiple variable names can be passed to
Import
as separate arguments or as words in a space-separated string.
The wildcard "*"
can be used to import all
available variables.
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 the current construction environment.
If
arg
is not a dictionary,
it is converted to one by calling
env.ParseFlags
on the argument
before the values are merged.
Note that
arg
must be a single value,
so multiple strings must
be passed in as a list,
not as separate arguments to
env.MergeFlags
.
If unique
is true (the default),
duplicate values are not stored.
When eliminating duplicate values,
any construction variables that end with
the string
PATH
keep the left-most unique value.
All other construction variables keep
the right-most unique value.
If unique
is false,
values are added even if they are duplicates.
Examples:
# Add an optimization flag to $CCFLAGS. env.MergeFlags('-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 # twice and merge the result 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
(target, ...
), env
.NoClean
(target, ...
)
Specifies a list of files or directories which should
not
be removed whenever the targets (or their dependencies)
are specified with the
-c
command line option.
The specified targets may be a list
or an individual target.
Multiple calls to
NoClean
are legal,
and prevent each specified target
from being removed by calls to the
-c
option.
Multiple files or directories should be specified
either as separate arguments to the
NoClean
method, or as a list.
NoClean
will also accept the return value of any of the construction environment
Builder methods.
Calling
NoClean
for a target overrides calling
Clean
for the same target,
and any targets passed to both functions will
not
be removed by the
-c
option.
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
a table of options and corresponding construction variables.
To provide alternative processing of the output of
command
,
you can suppply 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 -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 each given
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 to a single call to
Precious
.
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 path elements specified by newpath
to the given search path string or list name
in mapping envname
in the construction environment.
Supplying envname
is optional:
the default is the execution environment $ENV
.
Optional sep
is used as the search path separator,
the default is the platform's separator (os.pathsep
).
A path element will only appear once.
Any duplicates in newpath
are dropped,
keeping the first appearing (to preserve path order).
If delete_existing
is False
any addition duplicating an existing path element is ignored;
if delete_existing
is True
(the default) the existing value will
be dropped and the path element will be inserted at the beginning.
To help maintain uniqueness all paths are normalized (using
os.path.normpath
and
os.path.normcase
).
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
(see for details),
except that values are added to the front,
rather than the end, of any existing value of the construction variable,
and values already present in the construction variable
will not be added again.
If delete_existing
is True
,
the existing matching value is first removed,
and the requested value is inserted,
having the effect of moving such values 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 substition,
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, ...
)
This indicates that each given
target
should not be created by the build rule, and if the target is created,
an error will be generated. This is similar to the gnu make .PHONY
target. However, in the vast majority of cases, an
Alias
is more appropriate.
Multiple targets can be passed in to a single call to
Pseudo
.
PyPackageDir
(modulename
), env
.PyPackageDir
(modulename
)
This returns a Directory Node similar to Dir.
The python module / package is looked up and if located
the directory is returned for the location.
modulename
Is a named python package / module to
lookup the directory for it's location.
If
modulename
is a list, SCons returns a list of Dir nodes.
Construction variables are expanded in
modulename
.
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
)
Specifies that
directory
is a repository to be searched for files.
Multiple calls to
Repository
are legal,
and each one adds to the list of
repositories that will be searched.
To scons, a repository is a copy of the source tree, from the top-level directory on down, which may contain both source files and derived files that can be used to build targets in the local source tree. The canonical example would be an official source tree maintained by an integrator. If the repository contains derived files, then the derived files should have been built using scons, so that the repository contains the necessary signature information to allow scons to figure out when it is appropriate to use the repository copy of a derived file, instead of building one locally.
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.
In order to guarantee that a local copy
will be made,
use the
Local
method.
Requires
(target, prerequisite
), env
.Requires
(target, prerequisite
)Specifies an order-only relationship between the specified target file(s) and the specified prerequisite file(s). The prerequisite file(s) 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.
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 contaning 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
(scripts, [exports, variant_dir, duplicate, must_exist]
), env
.SConscript
(scripts, [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 one or more subsidiary SConscript (configuration) files.
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.
A single script may be specified as a string;
multiple scripts must be specified as a list of strings
(either explicitly or as created by
a function like
Split
).
Examples:
SConscript('SConscript') # run SConscript in the current directory SConscript('src/SConscript') # run SConscript in the src directory SConscript(['src/SConscript', 'doc/SConscript']) config = SConscript('MyConfig.py')
The other calling style is to omit the positional argument naming
scripts and instead specify a list of directory names using the
dirs
keyword argument.
In this case,
scons
will
execute a subsidiary configuration file named
SConscript
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 provides a string or list of strings representing
variable names, or a dictionary of named values, to export.
For the first calling style only, a second positional argument
will be interpreted as exports
; the
second calling style must use the keyword argument form
for exports
.
These variables are locally exported only to the called
SConscript file(s)
and do not affect the global pool of variables managed by the
Export
function.
The subsidiary SConscript files
must use the
Import
function to import the variables.
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
,
causes an exception to be raised if a requested
SConscript file is not found. The current default is
False
,
causing only a warning to be emitted, but this default is deprecated
(since 3.1).
For scripts which truly intend to be optional, transition to
explicitly supplying
must_exist=False
to the SConscript
call.
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
), env
.SConscriptChdir
(value
)By default, scons changes its working directory to the directory in which each subsidiary SConscript file lives. This behavior may be disabled by specifying either:
SConscriptChdir(0) env.SConscriptChdir(0)
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:
env = Environment() SConscriptChdir(0) SConscript('foo/SConscript') # will not chdir to foo env.SConscriptChdir(1) 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 meaure 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
)
Sets scons option variable name
to value
.
These options are all also settable via
command-line options but the variable name
may differ from the command-line option name -
see the table for correspondences.
A value set via command-line option will take
precedence over one set with SetOption
, which
allows setting a project default in the scripts and
temporarily overriding it via command line.
SetOption
calls can also be placed in the
site_init.py
file.
See the documentation in the manpage for the
corresponding command line option for information about each specific option.
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.
The settable variables with their associated command-line options are:
Settable name | Command-line options | Notes |
---|---|---|
clean |
-c ,
--clean ,
--remove
| |
diskcheck | --diskcheck | |
duplicate | --duplicate | |
experimental | --experimental | since 4.2 |
hash_chunksize | --hash-chunksize |
Actually sets 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 | --md5-chunksize | |
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 |
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
${
,
although if there is no ambiguity in recognizing the element,
the braces can be omitted.
A literal $ can be entered by
using $$.
expression
}
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, **kwargs]
), env
.Tool
(name, [toolpath, **kwargs]
)
Locates the tool specification module name
and returns a callable tool object for that tool.
The tool module is searched for in standard locations
and in any paths specified by the optional
toolpath
parameter.
The standard locations are SCons' own internal
path for tools plus the toolpath, if any (see the
Tools section in the manual page
for more details).
Any additional keyword arguments
kwargs
are passed
to the tool module's generate
function
during tool object construction.
When called, the tool object updates a construction environment with construction variables and arranges any other initialization needed to use the mechanisms that tool describes.
When the env.Tool
form is used,
the tool object is automatically called to update env
and the value of tool
is
appended to the $TOOLS
construction variable in that environment.
Examples:
env.Tool('gcc') env.Tool('opengl', toolpath=['build/tools'])
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.
The 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
Changed in SCons 4.2: env.Tool
now returns
the tool object, previously it did not return
(i.e. returned None
).
ValidateOptions
([throw_exception=False]
)
Check that all the options specified on the command line are either defined by SCons itself
or defined by calls to AddOption
.
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 you load those tools before you call ValidateOptions
.
If there are any command line options not defined, calling this function will cause SCons to issue an error message and then exit with an error exit status.
If the optional throw_exception
is True
, ValidateOptions
will raise a
SConsBadOptionError
exception. This would allow the calling
SConscript
logic can catch that exception and handle invalid options itself.
Example:
try: ValidateOptions(throw_exception=True) except SConsBadOptionError as e: print("Parser is SConsOptionParser:%s" % (isinstance(e.parser, SConsOptionParser))) print("Message is :%s" % e.opt_str) Exit(3)
This function is useful to force SCons to fail fast before you execute any expensive logic later in your build logic. For example if you specify build options via any flags, a simple typo could yield the incorrect build option throughout your entire build.
scons --compilers=mingw (the correct flag is --compiler)
Could cause SCons to run configure steps with the incorrect compiler. Costing developer time trying to track down why the configure logic failed with a compiler which should work.
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 result of
calling
str
(value
)
changes between SCons runs, any targets depending on
Value
(value
)
will be rebuilt.
(This is true even when using timestamps to decide if
files are up-to-date.)
When using timestamp source signatures, Value Nodes'
timestamps are equal to the system time when the Node is created.
name
can be provided as an alternative name
for the resulting Value
node; this is advised
if the value
parameter can't be converted to
a string.
The returned Value Node object has a
write
()
method that can be used to "build" a Value Node
by setting a new value.
The optional
built_value
argument can be specified
when the Value Node is created
to indicate the Node should already be considered
"built."
There is a corresponding
read
()
method that will return the built value of the Node.
Examples:
env = Environment() def create(target, source, env): # A function that will write a 'prefix=$SOURCE' # string into the file name specified as the # $TARGET. with open(str(target[0]), 'wb') as f: f.write('prefix=' + source[0].get_contents()) # Fetch the prefix= argument, if any, from the command # line, and use /usr/local as the default. prefix = ARGUMENTS.get('prefix', '/usr/local') # Attach a .Config() builder for the above function action # to the construction environment. env['BUILDERS']['Config'] = Builder(action = create) env.Config(target = 'package-config', source = Value(prefix)) def build_value(target, source, env): # A function that "builds" a Python Value by updating # the Python value with the contents of the file # specified as the source of the Builder call ($SOURCE). target[0].write(source[0].get_contents()) output = env.Value('before') input = env.Value('after') # Attach a .UpdateValue() builder for the above function # action to the construction environment. 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
may 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)
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.