SCons package#

Module contents#

Subpackages#

Submodules#

SCons.Action module#

SCons Actions.

Information about executing any sort of action that can build one or more target Nodes (typically files) from one or more source Nodes (also typically files) given a specific Environment.

The base class here is ActionBase. The base class supplies just a few utility methods and some generic methods for displaying information about an Action in response to the various commands that control printing.

A second-level base class is _ActionAction. This extends ActionBase by providing the methods that can be used to show and perform an action. True Action objects will subclass _ActionAction; Action factory class objects will subclass ActionBase.

The heavy lifting is handled by subclasses for the different types of actions we might execute:

CommandAction CommandGeneratorAction FunctionAction ListAction

The subclasses supply the following public interface methods used by other modules:

__call__()

THE public interface, “calling” an Action object executes the command or Python function. This also takes care of printing a pre-substitution command for debugging purposes.

get_contents()

Fetches the “contents” of an Action for signature calculation plus the varlist. This is what gets checksummed to decide if a target needs to be rebuilt because its action changed.

genstring()

Returns a string representation of the Action without command substitution, but allows a CommandGeneratorAction to generate the right action based on the specified target, source and env. This is used by the Signature subsystem (through the Executor) to obtain an (imprecise) representation of the Action operation for informative purposes.

Subclasses also supply the following methods for internal use within this module:

__str__()

Returns a string approximation of the Action; no variable substitution is performed.

execute()

The internal method that really, truly, actually handles the execution of a command or Python function. This is used so that the __call__() methods can take care of displaying any pre-substitution representations, and then execute an action without worrying about the specific Actions involved.

get_presig()

Fetches the “contents” of a subclass for signature calculation. The varlist is added to this to produce the Action’s contents. TODO(?): Change this to always return bytes and not str?

strfunction()

Returns a substituted string representation of the Action. This is used by the _ActionAction.show() command to display the command/function that will be executed to generate the target(s).

There is a related independent ActionCaller class that looks like a regular Action, and which serves as a wrapper for arbitrary functions that we want to let the user specify the arguments to now, but actually execute later (when an out-of-date check determines that it’s needed to be executed, for example). Objects of this class are returned by an ActionFactory class that provides a __call__() method as a convenient way for wrapping up the functions.

SCons.Action.Action(act, *args, **kw)[source]#

A factory for action objects.

class SCons.Action.ActionBase[source]#

Bases: ABC

Base class for all types of action objects that can be held by other objects (Builders, Executors, etc.) This provides the common methods for manipulating and combining those actions.

_abc_impl = <_abc._abc_data object>#
batch_key(env, target, source)#
genstring(target, source, env, executor=None) str[source]#
get_contents(target, source, env)[source]#
abstract get_implicit_deps(target, source, env, executor=None)[source]#
abstract get_presig(target, source, env, executor=None)[source]#
get_targets(env, executor)[source]#

Returns the type of targets ($TARGETS, $CHANGED_TARGETS) used by this action.

get_varlist(target, source, env, executor=None)[source]#
no_batch_key(env, target, source)[source]#
presub_lines(env)[source]#
class SCons.Action.ActionCaller(parent, args, kw)[source]#

Bases: object

A class for delaying calling an Action function with specific (positional and keyword) arguments until the Action is actually executed.

This class looks to the rest of the world like a normal Action object, but what it’s really doing is hanging on to the arguments until we have a target, source and env to use for the expansion.

get_contents(target, source, env)[source]#
strfunction(target, source, env)[source]#
subst(s, target, source, env)[source]#
subst_args(target, source, env)[source]#
subst_kw(target, source, env)[source]#
class SCons.Action.ActionFactory(actfunc, strfunc, convert=<function ActionFactory.<lambda>>)[source]#

Bases: object

A factory class that will wrap up an arbitrary function as an SCons-executable Action object.

The real heavy lifting here is done by the ActionCaller class. We just collect the (positional and keyword) arguments that we’re called with and give them to the ActionCaller object we create, so it can hang onto them until it needs them.

class SCons.Action.CommandAction(cmd, **kw)[source]#

Bases: _ActionAction

Class for command-execution actions.

_abc_impl = <_abc._abc_data object>#
_get_implicit_deps_heavyweight(target, source, env, executor, icd_int)[source]#

Heavyweight dependency scanning involves scanning more than just the first entry in an action string. The exact behavior depends on the value of icd_int. Only files are taken as implicit dependencies; directories are ignored.

If icd_int is an integer value, it specifies the number of entries to scan for implicit dependencies. Action strings are also scanned after a &&. So for example, if icd_int=2 and the action string is “cd <some_dir> && $PYTHON $SCRIPT_PATH <another_path>”, the implicit dependencies would be the path to the python binary and the path to the script.

If icd_int is None, all entries are scanned for implicit dependencies.

_get_implicit_deps_lightweight(target, source, env, executor)[source]#

Lightweight dependency scanning involves only scanning the first entry in an action string, even if it contains &&.

batch_key(env, target, source)#
execute(target, source, env, executor=None)[source]#

Execute a command action.

This will handle lists of commands as well as individual commands, because construction variable substitution may turn a single “command” into a list. This means that this class can actually handle lists of commands, even though that’s not how we use it externally.

genstring(target, source, env, executor=None) str#
get_contents(target, source, env)#
get_implicit_deps(target, source, env, executor=None)[source]#

Return the implicit dependencies of this action’s command line.

get_presig(target, source, env, executor=None)[source]#

Return the signature contents of this action’s command line.

This strips $(-$) and everything in between the string, since those parts don’t affect signatures.

get_targets(env, executor)#

Returns the type of targets ($TARGETS, $CHANGED_TARGETS) used by this action.

get_varlist(target, source, env, executor=None)#
no_batch_key(env, target, source)#
presub_lines(env)#
print_cmd_line(s, target, source, env) None#

In python 3, and in some of our tests, sys.stdout is a String io object, and it takes unicode strings only This code assumes s is a regular string.

process(target, source, env, executor=None, overrides: bool = False)[source]#
strfunction(target, source, env, executor=None, overrides: bool = False)[source]#
class SCons.Action.CommandGeneratorAction(generator, kw)[source]#

Bases: ActionBase

Class for command-generator actions.

_abc_impl = <_abc._abc_data object>#
_generate(target, source, env, for_signature, executor=None)[source]#
batch_key(env, target, source)[source]#
genstring(target, source, env, executor=None) str[source]#
get_contents(target, source, env)#
get_implicit_deps(target, source, env, executor=None)[source]#
get_presig(target, source, env, executor=None)[source]#

Return the signature contents of this action’s command line.

This strips $(-$) and everything in between the string, since those parts don’t affect signatures.

get_targets(env, executor)[source]#

Returns the type of targets ($TARGETS, $CHANGED_TARGETS) used by this action.

get_varlist(target, source, env, executor=None)[source]#
no_batch_key(env, target, source)#
presub_lines(env)#
class SCons.Action.FunctionAction(execfunction, kw)[source]#

Bases: _ActionAction

Class for Python function actions.

_abc_impl = <_abc._abc_data object>#
batch_key(env, target, source)#
execute(target, source, env, executor=None)[source]#
function_name()[source]#
genstring(target, source, env, executor=None) str#
get_contents(target, source, env)#
get_implicit_deps(target, source, env, executor=None)[source]#
get_presig(target, source, env, executor=None)[source]#

Return the signature contents of this callable action.

get_targets(env, executor)#

Returns the type of targets ($TARGETS, $CHANGED_TARGETS) used by this action.

get_varlist(target, source, env, executor=None)#
no_batch_key(env, target, source)#
presub_lines(env)#
print_cmd_line(s, target, source, env) None#

In python 3, and in some of our tests, sys.stdout is a String io object, and it takes unicode strings only This code assumes s is a regular string.

strfunction(target, source, env, executor=None)[source]#
class SCons.Action.LazyAction(var, kw)[source]#

Bases: CommandGeneratorAction, CommandAction

A LazyAction is a kind of hybrid generator and command action for strings of the form “$VAR”. These strings normally expand to other strings (think “$CCCOM” to “$CC -c -o $TARGET $SOURCE”), but we also want to be able to replace them with functions in the construction environment. Consequently, we want lazy evaluation and creation of an Action in the case of the function, but that’s overkill in the more normal case of expansion to other strings.

So we do this with a subclass that’s both a generator and a command action. The overridden methods all do a quick check of the construction variable, and if it’s a string we just call the corresponding CommandAction method to do the heavy lifting. If not, then we call the same-named CommandGeneratorAction method. The CommandGeneratorAction methods work by using the overridden _generate() method, that is, our own way of handling “generation” of an action based on what’s in the construction variable.

_abc_impl = <_abc._abc_data object>#
_generate(target, source, env, for_signature, executor=None)[source]#
_generate_cache(env)[source]#
_get_implicit_deps_heavyweight(target, source, env, executor, icd_int)#

Heavyweight dependency scanning involves scanning more than just the first entry in an action string. The exact behavior depends on the value of icd_int. Only files are taken as implicit dependencies; directories are ignored.

If icd_int is an integer value, it specifies the number of entries to scan for implicit dependencies. Action strings are also scanned after a &&. So for example, if icd_int=2 and the action string is “cd <some_dir> && $PYTHON $SCRIPT_PATH <another_path>”, the implicit dependencies would be the path to the python binary and the path to the script.

If icd_int is None, all entries are scanned for implicit dependencies.

_get_implicit_deps_lightweight(target, source, env, executor)#

Lightweight dependency scanning involves only scanning the first entry in an action string, even if it contains &&.

batch_key(env, target, source)#
execute(target, source, env, executor=None)#

Execute a command action.

This will handle lists of commands as well as individual commands, because construction variable substitution may turn a single “command” into a list. This means that this class can actually handle lists of commands, even though that’s not how we use it externally.

genstring(target, source, env, executor=None) str#
get_contents(target, source, env)#
get_implicit_deps(target, source, env, executor=None)[source]#

Return the implicit dependencies of this action’s command line.

get_parent_class(env)[source]#
get_presig(target, source, env, executor=None)[source]#

Return the signature contents of this action’s command line.

This strips $(-$) and everything in between the string, since those parts don’t affect signatures.

get_targets(env, executor)#

Returns the type of targets ($TARGETS, $CHANGED_TARGETS) used by this action.

get_varlist(target, source, env, executor=None)[source]#
no_batch_key(env, target, source)#
presub_lines(env)#
print_cmd_line(s, target, source, env) None#

In python 3, and in some of our tests, sys.stdout is a String io object, and it takes unicode strings only This code assumes s is a regular string.

process(target, source, env, executor=None, overrides: bool = False)#
strfunction(target, source, env, executor=None, overrides: bool = False)#
class SCons.Action.ListAction(actionlist)[source]#

Bases: ActionBase

Class for lists of other actions.

_abc_impl = <_abc._abc_data object>#
batch_key(env, target, source)#
genstring(target, source, env, executor=None) str[source]#
get_contents(target, source, env)#
get_implicit_deps(target, source, env, executor=None)[source]#
get_presig(target, source, env, executor=None)[source]#

Return the signature contents of this action list.

Simple concatenation of the signatures of the elements.

get_targets(env, executor)#

Returns the type of targets ($TARGETS, $CHANGED_TARGETS) used by this action.

get_varlist(target, source, env, executor=None)[source]#
no_batch_key(env, target, source)#
presub_lines(env)[source]#
class SCons.Action._ActionAction(cmdstr=<class 'SCons.Action._null'>, strfunction=<class 'SCons.Action._null'>, varlist=(), presub=<class 'SCons.Action._null'>, chdir=None, exitstatfunc=None, batch_key=None, targets: str = '$TARGETS', **kw)[source]#

Bases: ActionBase

Base class for actions that create output objects.

_abc_impl = <_abc._abc_data object>#
batch_key(env, target, source)#
genstring(target, source, env, executor=None) str#
get_contents(target, source, env)#
get_implicit_deps(target, source, env, executor=None)[source]#
get_presig(target, source, env, executor=None)[source]#
get_targets(env, executor)#

Returns the type of targets ($TARGETS, $CHANGED_TARGETS) used by this action.

get_varlist(target, source, env, executor=None)#
no_batch_key(env, target, source)#
presub_lines(env)#
print_cmd_line(s, target, source, env) None[source]#

In python 3, and in some of our tests, sys.stdout is a String io object, and it takes unicode strings only This code assumes s is a regular string.

SCons.Action._actionAppend(act1, act2)[source]#

Joins two actions together.

Mainly, it handles ListActions by concatenating into a single ListAction.

SCons.Action._callable_contents(obj) bytearray[source]#

Return the signature contents of a callable Python object.

SCons.Action._code_contents(code, docstring=None) bytearray[source]#

Return the signature contents of a code object.

By providing direct access to the code object of the function, Python makes this extremely easy. Hooray!

Unfortunately, older versions of Python include line number indications in the compiled byte code. Boo! So we remove the line number byte codes to prevent recompilations from moving a Python function.

See:

For info on what each co_ variable provides

The signature is as follows (should be byte/chars): co_argcount, len(co_varnames), len(co_cellvars), len(co_freevars), ( comma separated signature for each object in co_consts ), ( comma separated signature for each object in co_names ), ( The bytecode with line number bytecodes removed from co_code )

co_argcount - Returns the number of positional arguments (including arguments with default values). co_varnames - Returns a tuple containing the names of the local variables (starting with the argument names). co_cellvars - Returns a tuple containing the names of local variables that are referenced by nested functions. co_freevars - Returns a tuple containing the names of free variables. (?) co_consts - Returns a tuple containing the literals used by the bytecode. co_names - Returns a tuple containing the names used by the bytecode. co_code - Returns a string representing the sequence of bytecode instructions.

SCons.Action._do_create_action(act, kw)[source]#

The internal implementation for the Action factory method.

This handles the fact that passing lists to Action() itself has different semantics than passing lists as elements of lists. The former will create a ListAction, the latter will create a CommandAction by converting the inner list elements to strings.

SCons.Action._do_create_keywords(args, kw)[source]#

This converts any arguments after the action argument into their equivalent keywords and adds them to the kw argument.

SCons.Action._do_create_list_action(act, kw) ListAction[source]#

A factory for list actions.

Convert the input list act into Actions and then wrap them in a ListAction. If act has only a single member, return that member, not a ListAction. This is intended to allow a contained list to specify a command action without being processed into a list action.

SCons.Action._function_contents(func) bytearray[source]#

Return the signature contents of a function.

The signature is as follows (should be byte/chars): < _code_contents (see above) from func.__code__ > ,( comma separated _object_contents for function argument defaults) ,( comma separated _object_contents for any closure contents )

See also: https://docs.python.org/3/reference/datamodel.html
  • func.__code__ - The code object representing the compiled function body.

  • func.__defaults__ - A tuple containing default argument values for those arguments that have defaults, or None if no arguments have a default value

  • func.__closure__ - None or a tuple of cells that contain bindings for the function’s free variables.

class SCons.Action._null[source]#

Bases: object

SCons.Action._object_contents(obj) bytearray[source]#

Return the signature contents of any Python object.

We have to handle the case where object contains a code object since it can be pickled directly.

SCons.Action._object_instance_content(obj)[source]#

Returns consistant content for a action class or an instance thereof

Parameters:
  • obj Should be either and action class or an instance thereof

Returns:

bytearray or bytes representing the obj suitable for generating a signature from.

SCons.Action._resolve_shell_env(env, target, source)[source]#

Returns a resolved execution environment.

First get the execution environment. Then if SHELL_ENV_GENERATORS is set and is iterable, call each function to allow it to alter the created execution environment, passing each the returned execution environment from the previous call.

New in version 4.4.

SCons.Action._string_from_cmd_list(cmd_list)[source]#

Takes a list of command line arguments and returns a pretty representation for printing.

SCons.Action._subproc(scons_env, cmd, error='ignore', **kw)[source]#

Wrapper for subprocess.Popen which pulls from construction env.

Use for calls to subprocess which need to interpolate values from an SCons construction environment into the environment passed to subprocess. Adds an an error-handling argument. Adds ability to specify std{in,out,err} with “‘devnull’” tag.

Deprecated since version 4.6.

SCons.Action.default_exitstatfunc(s)[source]#
SCons.Action.get_default_ENV(env)[source]#

Returns an execution environment.

If there is one in env, just use it, else return the Default Environment, insantiated if necessary.

A fiddlin’ little function that has an import SCons.Environment which cannot be moved to the top level without creating an import loop. Since this import creates a local variable named SCons, it blocks access to the global variable, so we move it here to prevent complaints about local variables being used uninitialized.

SCons.Action.rfile(n)[source]#
SCons.Action.scons_subproc_run(scons_env, *args, **kwargs) CompletedProcess[source]#

Run an external command using an SCons execution environment.

SCons normally runs external build commands using subprocess, but does not harvest any output from such commands. This function is a thin wrapper around subprocess.run() allowing running a command in an SCons context (i.e. uses an “execution environment” rather than the user’s existing environment), and provides the ability to return any output in a subprocess.CompletedProcess instance (this must be selected by setting stdout and/or stderr to PIPE, or setting capture_output=True - see Keyword Arguments). Typical use case is to run a tool’s “version” option to find out the installed version.

If supplied, the env keyword argument provides an execution environment to process into appropriate form before it is supplied to subprocess; if omitted, scons_env is used to derive a suitable default. The other keyword arguments are passed through, except that the SCons legacy error keyword is remapped to the subprocess check keyword; if both are omitted check=False will be passed. The caller is responsible for setting up the desired arguments for subprocess.run().

This function retains the legacy behavior of returning something vaguely usable even in the face of complete failure, unless check=True (in which case an error is allowed to be raised): it synthesizes a CompletedProcess instance in this case.

A subset of interesting keyword arguments follows; see the Python documentation of subprocess for the complete list.

Keyword Arguments:
  • stdout – (and stderr, stdin) if set to subprocess.PIPE. send input to or collect output from the relevant stream in the subprocess; the default None does no redirection (i.e. output or errors may go to the console or log file, but is not captured); if set to subprocess.DEVNULL they are explicitly thrown away. capture_output=True is a synonym for setting both stdout and stderr to PIPE.

  • text – open stdin, stdout, stderr in text mode. Default is binary mode. universal_newlines is a synonym.

  • encoding – specifies an encoding. Changes to text mode.

  • errors – specified error handling. Changes to text mode.

  • input – a byte sequence to be passed to stdin, unless text mode is enabled, in which case it must be a string.

  • shell – if true, the command is executed through the shell.

  • check – if true and the subprocess exits with a non-zero exit code, raise a subprocess.CalledProcessError exception. Otherwise (the default) in case of an OSError, report the exit code in the CompletedProcess instance.

New in version 4.6.

SCons.Builder module#

SCons.Builder

Builder object subsystem.

A Builder object is a callable that encapsulates information about how to execute actions to create a target Node (file) from source Nodes (files), and how to create those dependencies for tracking.

The main entry point here is the Builder() factory method. This provides a procedural interface that creates the right underlying Builder object based on the keyword arguments supplied and the types of the arguments.

The goal is for this external interface to be simple enough that the vast majority of users can create new Builders as necessary to support building new types of files in their configurations, without having to dive any deeper into this subsystem.

The base class here is BuilderBase. This is a concrete base class which does, in fact, represent the Builder objects that we (or users) create.

There is also a proxy that looks like a Builder:

CompositeBuilder

This proxies for a Builder with an action that is actually a dictionary that knows how to map file suffixes to a specific action. This is so that we can invoke different actions (compilers, compile options) for different flavors of source files.

Builders and their proxies have the following public interface methods used by other modules:

  • __call__()

    THE public interface. Calling a Builder object (with the use of internal helper methods) sets up the target and source dependencies, appropriate mapping to a specific action, and the environment manipulation necessary for overridden construction variable. This also takes care of warning about possible mistakes in keyword arguments.

  • add_emitter()

    Adds an emitter for a specific file suffix, used by some Tool modules to specify that (for example) a yacc invocation on a .y can create a .h and a .c file.

  • add_action()

    Adds an action for a specific file suffix, heavily used by Tool modules to add their specific action(s) for turning a source file into an object file to the global static and shared object file Builders.

There are the following methods for internal use within this module:

  • _execute()

    The internal method that handles the heavily lifting when a Builder is called. This is used so that the __call__() methods can set up warning about possible mistakes in keyword-argument overrides, and then execute all of the steps necessary so that the warnings only occur once.

  • get_name()

    Returns the Builder’s name within a specific Environment, primarily used to try to return helpful information in error messages.

  • adjust_suffix()

  • get_prefix()

  • get_suffix()

  • get_src_suffix()

  • set_src_suffix()

    Miscellaneous stuff for handling the prefix and suffix manipulation we use in turning source file names into target file names.

SCons.Builder.Builder(**kw)[source]#

A factory for builder objects.

class SCons.Builder.BuilderBase(action=None, prefix: str = '', suffix: str = '', src_suffix: str = '', target_factory=None, source_factory=None, target_scanner=None, source_scanner=None, emitter=None, multi: int = 0, env=None, single_source: bool = False, name=None, chdir=<class 'SCons.Builder._Null'>, is_explicit: bool = True, src_builder=None, ensure_suffix: bool = False, **overrides)[source]#

Bases: object

Base class for Builders, objects that create output nodes (files) from input nodes (files).

_adjustixes(files, pre, suf, ensure_suffix: bool = False)[source]#
_create_nodes(env, target=None, source=None)[source]#

Create and return lists of target and source nodes.

_execute(env, target, source, overwarn={}, executor_kw={})[source]#
_get_sdict(env)[source]#

Returns a dictionary mapping all of the source suffixes of all src_builders of this Builder to the underlying Builder that should be called first.

This dictionary is used for each target specified, so we save a lot of extra computation by memoizing it for each construction environment.

Note that this is re-computed each time, not cached, because there might be changes to one of our source Builders (or one of their source Builders, and so on, and so on…) that we can’t “see.”

The underlying methods we call cache their computed values, though, so we hope repeatedly aggregating them into a dictionary like this won’t be too big a hit. We may need to look for a better way to do this if performance data show this has turned into a significant bottleneck.

_get_src_builders_key(env)[source]#
_subst_src_suffixes_key(env)[source]#
add_emitter(suffix, emitter) None[source]#

Add a suffix-emitter mapping to this Builder.

This assumes that emitter has been initialized with an appropriate dictionary type, and will throw a TypeError if not, so the caller is responsible for knowing that this is an appropriate method to call for the Builder in question.

add_src_builder(builder) None[source]#

Add a new Builder to the list of src_builders.

This requires wiping out cached values so that the computed lists of source suffixes get re-calculated.

adjust_suffix(suff)[source]#
get_name(env)[source]#

Attempts to get the name of the Builder.

Look at the BUILDERS variable of env, expecting it to be a dictionary containing this Builder, and return the key of the dictionary. If there’s no key, then return a directly-configured name (if there is one) or the name of the class (by default).

get_prefix(env, sources=[])[source]#
get_src_builders(env)[source]#

Returns the list of source Builders for this Builder.

This exists mainly to look up Builders referenced as strings in the ‘BUILDER’ variable of the construction environment and cache the result.

get_src_suffix(env)[source]#

Get the first src_suffix in the list of src_suffixes.

get_suffix(env, sources=[])[source]#
set_src_suffix(src_suffix) None[source]#
set_suffix(suffix) None[source]#
splitext(path, env=None)[source]#
src_builder_sources(env, source, overwarn={})[source]#
src_suffixes(env)[source]#

Returns the list of source suffixes for all src_builders of this Builder.

This is essentially a recursive descent of the src_builder “tree.” (This value isn’t cached because there may be changes in a src_builder many levels deep that we can’t see.)

subst_src_suffixes(env)[source]#

The suffix list may contain construction variable expansions, so we have to evaluate the individual strings. To avoid doing this over and over, we memoize the results for each construction environment.

class SCons.Builder.CallableSelector[source]#

Bases: Selector

A callable dictionary that will, in turn, call the value it finds if it can.

clear() None.  Remove all items from D.#
copy() a shallow copy of D#
fromkeys(value=None, /)#

Create a new dictionary with keys from iterable and values set to value.

get(key, default=None, /)#

Return the value for key if key is in the dictionary, else default.

items() a set-like object providing a view on D's items#
keys() a set-like object providing a view on D's keys#
pop(k[, d]) v, remove specified key and return the corresponding value.#

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem()#

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.

setdefault(key, default=None, /)#

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update([E, ]**F) None.  Update D from dict/iterable E and F.#

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values() an object providing a view on D's values#
class SCons.Builder.CompositeBuilder(builder, cmdgen)[source]#

Bases: Proxy

A Builder Proxy whose main purpose is to always have a DictCmdGenerator as its action, and to provide access to the DictCmdGenerator’s add_action() method.

__getattr__(name)#

Retrieve an attribute from the wrapped object.

Raises:

AttributeError – if attribute name doesn’t exist.

add_action(suffix, action) None[source]#
get()#

Retrieve the entire wrapped object

class SCons.Builder.DictCmdGenerator(mapping=None, source_ext_match: bool = True)[source]#

Bases: Selector

This is a callable class that can be used as a command generator function. It holds on to a dictionary mapping file suffixes to Actions. It uses that dictionary to return the proper action based on the file suffix of the source file.

add_action(suffix, action) None[source]#

Add a suffix-action pair to the mapping.

clear() None.  Remove all items from D.#
copy() a shallow copy of D#
fromkeys(value=None, /)#

Create a new dictionary with keys from iterable and values set to value.

get(key, default=None, /)#

Return the value for key if key is in the dictionary, else default.

items() a set-like object providing a view on D's items#
keys() a set-like object providing a view on D's keys#
pop(k[, d]) v, remove specified key and return the corresponding value.#

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem()#

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.

setdefault(key, default=None, /)#

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

src_suffixes()[source]#
update([E, ]**F) None.  Update D from dict/iterable E and F.#

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values() an object providing a view on D's values#
class SCons.Builder.DictEmitter[source]#

Bases: Selector

A callable dictionary that maps file suffixes to emitters. When called, it finds the right emitter in its dictionary for the suffix of the first source file, and calls that emitter to get the right lists of targets and sources to return. If there’s no emitter for the suffix in its dictionary, the original target and source are returned.

clear() None.  Remove all items from D.#
copy() a shallow copy of D#
fromkeys(value=None, /)#

Create a new dictionary with keys from iterable and values set to value.

get(key, default=None, /)#

Return the value for key if key is in the dictionary, else default.

items() a set-like object providing a view on D's items#
keys() a set-like object providing a view on D's keys#
pop(k[, d]) v, remove specified key and return the corresponding value.#

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem()#

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.

setdefault(key, default=None, /)#

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

update([E, ]**F) None.  Update D from dict/iterable E and F.#

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

values() an object providing a view on D's values#
class SCons.Builder.EmitterProxy(var)[source]#

Bases: object

This is a callable class that can act as a Builder emitter. It holds on to a string that is a key into an Environment dictionary, and will look there at actual build time to see if it holds a callable. If so, we will call that as the actual emitter.

class SCons.Builder.ListEmitter(initlist=None)[source]#

Bases: UserList

A callable list of emitters that calls each in sequence, returning the result.

_abc_impl = <_abc._abc_data object>#
append(item)#

S.append(value) – append value to the end of the sequence

clear() None -- remove all items from S#
copy()#
count(value) integer -- return number of occurrences of value#
extend(other)#

S.extend(iterable) – extend sequence by appending elements from the iterable

index(value[, start[, stop]]) integer -- return first index of value.#

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

insert(i, item)#

S.insert(index, value) – insert value before index

pop([index]) item -- remove and return item at index (default last).#

Raise IndexError if list is empty or index is out of range.

remove(item)#

S.remove(value) – remove first occurrence of value. Raise ValueError if the value is not present.

reverse()#

S.reverse() – reverse IN PLACE

sort(*args, **kwds)#
class SCons.Builder.OverrideWarner(mapping)[source]#

Bases: UserDict

A class for warning about keyword arguments that we use as overrides in a Builder call.

This class exists to handle the fact that a single Builder call can actually invoke multiple builders. This class only emits the warnings once, no matter how many Builders are invoked.

_abc_impl = <_abc._abc_data object>#
clear() None.  Remove all items from D.#
copy()#
classmethod fromkeys(iterable, value=None)#
get(k[, d]) D[k] if k in D, else d.  d defaults to None.#
items() a set-like object providing a view on D's items#
keys() a set-like object providing a view on D's keys#
pop(k[, d]) v, remove specified key and return the corresponding value.#

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() (k, v), remove and return some (key, value) pair#

as a 2-tuple; but raise KeyError if D is empty.

setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D#
update([E, ]**F) None.  Update D from mapping/iterable E and F.#

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values() an object providing a view on D's values#
warn() None[source]#
class SCons.Builder._Null[source]#

Bases: object

SCons.Builder._node_errors(builder, env, tlist, slist)[source]#

Validate that the lists of target and source nodes are legal for this builder and environment. Raise errors or issue warnings as appropriate.

SCons.Builder._null#

alias of _Null

SCons.Builder.is_a_Builder(obj) bool[source]#

“Returns True if the specified obj is one of our Builder classes.

The test is complicated a bit by the fact that CompositeBuilder is a proxy, not a subclass of BuilderBase.

SCons.Builder.match_splitext(path, suffixes=[])[source]#

SCons.CacheDir module#

CacheDir support

class SCons.CacheDir.CacheDir(path)[source]#

Bases: object

CacheDebug(fmt, target, cachefile) None[source]#
_readconfig(path)[source]#

Read the cache config.

If directory or config file do not exist, create. Take advantage of Py3 capability in os.makedirs() and in file open(): just try the operation and handle failure appropriately.

Omit the check for old cache format, assume that’s old enough there will be none of those left to worry about.

Parameters:

path – path to the cache directory

cachepath(node) tuple[source]#

Return where to cache a file.

Given a Node, obtain the configured cache directory and the path to the cached file, which is generated from the node’s build signature. If caching is not enabled for the None, return a tuple of None.

classmethod copy_from_cache(env, src, dst) str[source]#

Copy a file from cache.

classmethod copy_to_cache(env, src, dst) str[source]#

Copy a file to cache.

Just use the FS copy2 (“with metadata”) method, except do an additional check and if necessary a chmod to ensure the cachefile is writeable, to forestall permission problems if the cache entry is later updated.

get_cachedir_csig(node)[source]#
property hit_ratio: float#
is_enabled() bool[source]#
is_readonly() bool[source]#
property misses: int#
push(node)[source]#
push_if_forced(node)[source]#
retrieve(node) bool[source]#

Retrieve a node from cache.

Returns True if a successful retrieval resulted.

This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in built().

Note that there’s a special trick here with the execute flag (one that’s not normally done for other actions). Basically if the user requested a no_exec (-n) build, then SCons.Action.execute_actions is set to 0 and when any action is called, it does its showing but then just returns zero instead of actually calling the action execution operation. The problem for caching is that if the file does NOT exist in cache then the CacheRetrieveString won’t return anything to show for the task, but the Action.__call__ won’t call CacheRetrieveFunc; instead it just returns zero, which makes the code below think that the file was successfully retrieved from the cache, therefore it doesn’t do any subsequent building. However, the CacheRetrieveString didn’t print anything because it didn’t actually exist in the cache, and no more build actions will be performed, so the user just sees nothing. The fix is to tell Action.__call__ to always execute the CacheRetrieveFunc and then have the latter explicitly check SCons.Action.execute_actions itself.

SCons.CacheDir.CachePushFunc(target, source, env)[source]#
SCons.CacheDir.CacheRetrieveFunc(target, source, env) int[source]#
SCons.CacheDir.CacheRetrieveString(target, source, env) None[source]#

SCons.Conftest module#

Autoconf-like configuration support

The purpose of this module is to define how a check is to be performed.

A context class is used that defines functions for carrying out the tests, logging and messages. The following methods and members must be present:

context.Display(msg)

Function called to print messages that are normally displayed for the user. Newlines are explicitly used. The text should also be written to the logfile!

context.Log(msg)

Function called to write to a log file.

context.BuildProg(text, ext)

Function called to build a program, using “ext” for the file extension. Must return an empty string for success, an error message for failure. For reliable test results building should be done just like an actual program would be build, using the same command and arguments (including configure results so far).

context.CompileProg(text, ext)

Function called to compile a program, using “ext” for the file extension. Must return an empty string for success, an error message for failure. For reliable test results compiling should be done just like an actual source file would be compiled, using the same command and arguments (including configure results so far).

context.AppendLIBS(lib_name_list)

Append “lib_name_list” to the value of LIBS. “lib_namelist” is a list of strings. Return the value of LIBS before changing it (any type can be used, it is passed to SetLIBS() later.)

context.PrependLIBS(lib_name_list)

Prepend “lib_name_list” to the value of LIBS. “lib_namelist” is a list of strings. Return the value of LIBS before changing it (any type can be used, it is passed to SetLIBS() later.)

context.SetLIBS(value)

Set LIBS to “value”. The type of “value” is what AppendLIBS() returned. Return the value of LIBS before changing it (any type can be used, it is passed to SetLIBS() later.)

context.headerfilename

Name of file to append configure results to, usually “confdefs.h”. The file must not exist or be empty when starting. Empty or None to skip this (some tests will not work!).

context.config_h (may be missing).

If present, must be a string, which will be filled with the contents of a config_h file.

context.vardict

Dictionary holding variables used for the tests and stores results from the tests, used for the build commands. Normally contains “CC”, “LIBS”, “CPPFLAGS”, etc.

context.havedict

Dictionary holding results from the tests that are to be used inside a program. Names often start with “HAVE_”. These are zero (feature not present) or one (feature present). Other variables may have any value, e.g., “PERLVERSION” can be a number and “SYSTEMNAME” a string.

SCons.Conftest.CheckBuilder(context, text=None, language=None)[source]#

Configure check to see if the compiler works. Note that this uses the current value of compiler and linker flags, make sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly. “language” should be “C” or “C++” and is used to select the compiler. Default is “C”. “text” may be used to specify the code to be build. Returns an empty string for success, an error message for failure.

SCons.Conftest.CheckCC(context)[source]#

Configure check for a working C compiler.

This checks whether the C compiler, as defined in the $CC construction variable, can compile a C source file. It uses the current $CCCOM value too, so that it can test against non working flags.

SCons.Conftest.CheckCXX(context)[source]#

Configure check for a working CXX compiler.

This checks whether the CXX compiler, as defined in the $CXX construction variable, can compile a CXX source file. It uses the current $CXXCOM value too, so that it can test against non working flags.

SCons.Conftest.CheckDeclaration(context, symbol, includes=None, language=None)[source]#

Checks whether symbol is declared.

Use the same test as autoconf, that is test whether the symbol is defined as a macro or can be used as an r-value.

Parameters:
  • symbol – str the symbol to check

  • includes – str Optional “header” can be defined to include a header file.

  • language – str only C and C++ supported.

Returns:

bool

True if the check failed, False if succeeded.

Return type:

status

SCons.Conftest.CheckFunc(context, function_name, header=None, language=None)[source]#

Configure check for a function “function_name”. “language” should be “C” or “C++” and is used to select the compiler. Default is “C”. Optional “header” can be defined to define a function prototype, include a header file or anything else that comes before main(). Sets HAVE_function_name in context.havedict according to the result. Note that this uses the current value of compiler and linker flags, make sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly. Returns an empty string for success, an error message for failure.

SCons.Conftest.CheckHeader(context, header_name, header=None, language=None, include_quotes=None)[source]#

Configure check for a C or C++ header file “header_name”. Optional “header” can be defined to do something before including the header file (unusual, supported for consistency). “language” should be “C” or “C++” and is used to select the compiler. Default is “C”. Sets HAVE_header_name in context.havedict according to the result. Note that this uses the current value of compiler and linker flags, make sure $CFLAGS and $CPPFLAGS are set correctly. Returns an empty string for success, an error message for failure.

SCons.Conftest.CheckLib(context, libs, func_name=None, header=None, extra_libs=None, call=None, language=None, autoadd: int = 1, append: bool = True, unique: bool = False)[source]#

Configure check for a C or C++ libraries “libs”. Searches through the list of libraries, until one is found where the test succeeds. Tests if “func_name” or “call” exists in the library. Note: if it exists in another library the test succeeds anyway! Optional “header” can be defined to include a header file. If not given a default prototype for “func_name” is added. Optional “extra_libs” is a list of library names to be added after “lib_name” in the build command. To be used for libraries that “lib_name” depends on. Optional “call” replaces the call to “func_name” in the test code. It must consist of complete C statements, including a trailing “;”. Both “func_name” and “call” arguments are optional, and in that case, just linking against the libs is tested. “language” should be “C” or “C++” and is used to select the compiler. Default is “C”. Note that this uses the current value of compiler and linker flags, make sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly. Returns an empty string for success, an error message for failure.

SCons.Conftest.CheckMember(context, aggregate_member, header=None, language=None)[source]#

Configure check for a C or C++ member “aggregate_member”. Optional “header” can be defined to include a header file. “language” should be “C” or “C++” and is used to select the compiler. Default is “C”. Note that this uses the current value of compiler and linker flags, make sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly.

Parameters:
  • aggregate_member – str the member to check. For example, ‘struct tm.tm_gmtoff’.

  • includes – str Optional “header” can be defined to include a header file.

  • language – str only C and C++ supported.

Returns the status (0 or False = Passed, True/non-zero = Failed).

SCons.Conftest.CheckProg(context, prog_name)[source]#

Configure check for a specific program.

Check whether program prog_name exists in path. If it is found, returns the path for it, otherwise returns None.

SCons.Conftest.CheckSHCC(context)[source]#

Configure check for a working shared C compiler.

This checks whether the C compiler, as defined in the $SHCC construction variable, can compile a C source file. It uses the current $SHCCCOM value too, so that it can test against non working flags.

SCons.Conftest.CheckSHCXX(context)[source]#

Configure check for a working shared CXX compiler.

This checks whether the CXX compiler, as defined in the $SHCXX construction variable, can compile a CXX source file. It uses the current $SHCXXCOM value too, so that it can test against non working flags.

SCons.Conftest.CheckType(context, type_name, fallback=None, header=None, language=None)[source]#

Configure check for a C or C++ type “type_name”. Optional “header” can be defined to include a header file. “language” should be “C” or “C++” and is used to select the compiler. Default is “C”. Sets HAVE_type_name in context.havedict according to the result. Note that this uses the current value of compiler and linker flags, make sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly. Returns an empty string for success, an error message for failure.

SCons.Conftest.CheckTypeSize(context, type_name, header=None, language=None, expect=None)[source]#

This check can be used to get the size of a given type, or to check whether the type is of expected size.

Parameters:
  • type (-) – str the type to check

  • includes (-) – sequence list of headers to include in the test code before testing the type

  • language (-) – str ‘C’ or ‘C++’

  • expect (-) – int if given, will test wether the type has the given number of bytes. If not given, will automatically find the size.

  • Returns

    statusint

    0 if the check failed, or the found size of the type if the check succeeded.

SCons.Conftest._Have(context, key, have, comment=None) None[source]#

Store result of a test in context.havedict and context.headerfilename.

Parameters:
  • key - is a “HAVE_abc” name. It is turned into all CAPITALS and non-alphanumerics are replaced by an underscore.

  • have - value as it should appear in the header file, include quotes when desired and escape special characters!

  • comment is the C comment to add above the line defining the symbol (the comment is automatically put inside a /* */). If None, no comment is added.

The value of “have” can be:
  • 1 - Feature is defined, add “#define key”.

  • 0 - Feature is not defined, add “/* #undef key */”. Adding “undef” is what autoconf does. Not useful for the compiler, but it shows that the test was done.

  • number - Feature is defined to this number “#define key have”. Doesn’t work for 0 or 1, use a string then.

  • string - Feature is defined to this string “#define key have”.

SCons.Conftest._LogFailed(context, text, msg) None[source]#

Write to the log about a failed program. Add line numbers, so that error messages can be understood.

SCons.Conftest._YesNoResult(context, ret, key, text, comment=None) None[source]#

Handle the result of a test with a “yes” or “no” result.

Parameters:
  • ret is the return value: empty if OK, error message when not.

  • key is the name of the symbol to be defined (HAVE_foo).

  • text is the source code of the program used for testing.

  • comment is the C comment to add above the line defining the symbol (the comment is automatically put inside a /* */). If None, no comment is added.

SCons.Conftest._check_empty_program(context, comp, text, language, use_shared: bool = False)[source]#

Return 0 on success, 1 otherwise.

SCons.Conftest._lang2suffix(lang)[source]#

Convert a language name to a suffix. When “lang” is empty or None C is assumed. Returns a tuple (lang, suffix, None) when it works. For an unrecognized language returns (None, None, msg).

Where:
  • lang = the unified language name

  • suffix = the suffix, including the leading dot

  • msg = an error message

SCons.Debug module#

Code for debugging SCons internal things.

Shouldn’t be needed by most users. Quick shortcuts:

from SCons.Debug import caller_trace caller_trace()

SCons.Debug.Trace(msg, tracefile=None, mode: str = 'w', tstamp: bool = False) None[source]#

Write a trace message.

Write messages when debugging which do not interfere with stdout. Useful in tests, which monitor stdout and would break with unexpected output. Trace messages can go to the console (which is opened as a file), or to a disk file; the tracefile argument persists across calls unless overridden.

Parameters:
  • tracefile – file to write trace message to. If omitted, write to the previous trace file (default: console).

  • mode – file open mode (default: ‘w’)

  • tstamp – write relative timestamps with trace. Outputs time since scons was started, and time since last trace (default: False)

SCons.Debug._dump_one_caller(key, file, level: int = 0) None[source]#
SCons.Debug.caller_stack()[source]#

return caller’s stack

SCons.Debug.caller_trace(back: int = 0) None[source]#

Trace caller stack and save info into global dicts, which are printed automatically at the end of SCons execution.

SCons.Debug.countLoggedInstances(classes, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>) None[source]#
SCons.Debug.dumpLoggedInstances(classes, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>) None[source]#
SCons.Debug.dump_caller_counts(file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>) None[source]#
SCons.Debug.fetchLoggedInstances(classes: str = '*')[source]#
SCons.Debug.func_shorten(func_tuple)[source]#
SCons.Debug.listLoggedInstances(classes, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>) None[source]#
SCons.Debug.logInstanceCreation(instance, name=None) None[source]#
SCons.Debug.memory() int[source]#
SCons.Debug.string_to_classes(s)[source]#

SCons.Defaults module#

Builders and other things for the local site.

Here’s where we’ll duplicate the functionality of autoconf until we move it into the installation procedure or use something like qmconf.

The code that reads the registry to find MSVC components was borrowed from distutils.msvccompiler.

SCons.Defaults.DefaultEnvironment(*args, **kwargs)[source]#

Construct the global (“default”) construction environment.

The environment is provisioned with the values from kwargs.

After the environment is created, this function is replaced with a reference to _fetch_DefaultEnvironment() which efficiently returns the initialized default construction environment without checking for its existence.

Historically, some parts of the code held references to this function. Thus it still has the existence check for _default_env rather than just blindly creating the environment and overwriting itself.

class SCons.Defaults.NullCmdGenerator(cmd)[source]#

Bases: object

Callable class for use as a no-effect command generator.

The __call__ method for this class simply returns the thing you instantiated it with. Example usage:

env["DO_NOTHING"] = NullCmdGenerator
env["LINKCOM"] = "${DO_NOTHING('$LINK $SOURCES $TARGET')}"
SCons.Defaults.SharedFlagChecker(source, target, env)[source]#
SCons.Defaults.SharedObjectEmitter(target, source, env)[source]#
SCons.Defaults.StaticObjectEmitter(target, source, env)[source]#
class SCons.Defaults.Variable_Method_Caller(variable, method)[source]#

Bases: object

A class for finding a construction variable on the stack and calling one of its methods.

Used to support “construction variables” appearing in string eval``s that actually stand in for methods--specifically, the use of "RDirs" in a call to :func:`_concat` that should actually execute the ``TARGET.RDirs method.

Historical note: This was formerly supported by creating a little “build dictionary” that mapped RDirs to the method, but this got in the way of Memoizing construction environments, because we had to create new environment objects to hold the variables.

SCons.Defaults.__lib_either_version_flag(env, version_var1, version_var2, flags_var)[source]#

if $version_var1 or $version_var2 is not empty, returns env[flags_var], otherwise returns None :param env: :param version_var1: :param version_var2: :param flags_var: :return:

SCons.Defaults.__libversionflags(env, version_var, flags_var)[source]#

if version_var is not empty, returns env[flags_var], otherwise returns None :param env: :param version_var: :param flags_var: :return:

SCons.Defaults._concat(prefix, items_iter, suffix, env, f=<function <lambda>>, target=None, source=None, affect_signature: bool = True)[source]#

Creates a new list from ‘items_iter’ by first interpolating each element in the list using the ‘env’ dictionary and then calling f on the list, and finally calling _concat_ixes to concatenate ‘prefix’ and ‘suffix’ onto each element of the list.

SCons.Defaults._concat_ixes(prefix, items_iter, suffix, env)[source]#

Creates a new list from ‘items_iter’ by concatenating the ‘prefix’ and ‘suffix’ arguments onto each element of the list. A trailing space on ‘prefix’ or leading space on ‘suffix’ will cause them to be put into separate list elements rather than being concatenated.

SCons.Defaults._defines(prefix, defs, suffix, env, target=None, source=None, c=<function _concat_ixes>)[source]#

A wrapper around _concat_ixes() that turns a list or string into a list of C preprocessor command-line definitions.

SCons.Defaults._fetch_DefaultEnvironment(*args, **kwargs)[source]#

Returns the already-created default construction environment.

SCons.Defaults._stripixes(prefix: str, items, suffix: str, stripprefixes: List[str], stripsuffixes: List[str], env, literal_prefix: str = '', c: Callable[[list], list] = None) list[source]#

Returns a list with text added to items after first stripping them.

A companion to _concat_ixes(), used by tools (like the GNU linker) that need to turn something like libfoo.a into -lfoo. stripprefixes and stripsuffixes are stripped from items. Calls function c to postprocess the result.

Parameters:
  • prefix – string to prepend to elements

  • items – string or iterable to transform

  • suffix – string to append to elements

  • stripprefixes – prefix string(s) to strip from elements

  • stripsuffixes – suffix string(s) to strip from elements

  • env – construction environment for variable interpolation

  • c – optional function to perform a transformation on the list. The default is None, which will select _concat_ixes().

SCons.Defaults.chmod_func(dest, mode) None[source]#

Implementation of the Chmod action function.

mode can be either an integer (normally expressed in octal mode, as in 0o755) or a string following the syntax of the POSIX chmod command (for example “ugo+w”). The latter must be converted, since the underlying Python only takes the numeric form.

SCons.Defaults.chmod_strfunc(dest, mode) str[source]#

strfunction for the Chmod action function.

SCons.Defaults.copy_func(dest, src, symlinks: bool = True) int[source]#

Implementation of the Copy action function.

Copies src to dest. If src is a list, dest must be a directory, or not exist (will be created).

Since Python shutil methods, which know nothing about SCons Nodes, will be called to perform the actual copying, args are converted to strings first.

If symlinks evaluates true, then a symbolic link will be shallow copied and recreated as a symbolic link; otherwise, copying a symbolic link will be equivalent to copying the symbolic link’s final target regardless of symbolic link depth.

SCons.Defaults.copy_strfunc(dest, src, symlinks: bool = True) str[source]#

strfunction for the Copy action function.

SCons.Defaults.delete_func(dest, must_exist: bool = False) None[source]#

Implementation of the Delete action function.

Lets the Python os.unlink() raise an error if dest does not exist, unless must_exist evaluates false (the default).

SCons.Defaults.delete_strfunc(dest, must_exist: bool = False) str[source]#

strfunction for the Delete action function.

SCons.Defaults.get_paths_str(dest) str[source]#

Generates a string from dest for use in a strfunction.

If dest is a list, manually converts each elem to a string.

SCons.Defaults.mkdir_func(dest) None[source]#

Implementation of the Mkdir action function.

SCons.Defaults.move_func(dest, src) None[source]#

Implementation of the Move action function.

SCons.Defaults.processDefines(defs) List[str][source]#

Return list of strings for preprocessor defines from defs.

Resolves the different forms CPPDEFINES can be assembled in: if the Append/Prepend routines are used beyond a initial setting it will be a deque, but if written to only once (Environment initializer, or direct write) it can be a multitude of types.

Any prefix/suffix is handled elsewhere (usually _concat_ixes()).

Changed in version 4.5.0: Bare tuples are now treated the same as tuple-in-sequence, assumed to describe a valued macro. Bare strings are now split on space. A dictionary is no longer sorted before handling.

SCons.Defaults.touch_func(dest) None[source]#

Implementation of the Touch action function.

SCons.Environment module#

Base class for construction Environments.

These are the primary objects used to communicate dependency and construction information to the build engine.

Keyword arguments supplied when the construction Environment is created are construction variables used to initialize the Environment.

class SCons.Environment.Base(platform=None, tools=None, toolpath=None, variables=None, parse_flags=None, **kw)[source]#

Bases: SubstitutionEnvironment

Base class for “real” construction Environments.

These are the primary objects used to communicate dependency and construction information to the build engine.

Keyword arguments supplied when the construction Environment is created are construction variables used to initialize the Environment.

Action(*args, **kw)[source]#
AddMethod(function, name=None) None#

Adds the specified function as a method of this construction environment with the specified name. If the name is omitted, the default name is the name of the function itself.

AddPostAction(files, action)[source]#
AddPreAction(files, action)[source]#
Alias(target, source=[], action=None, **kw)[source]#
AlwaysBuild(*targets)[source]#
Append(**kw) None[source]#

Append values to construction variables in an Environment.

The variable is created if it is not already present.

AppendENVPath(name, newpath, envname: str = 'ENV', sep=':', delete_existing: bool = False) None[source]#

Append path elements to the path name in the envname dictionary for this environment. Will only add any particular path once, and will normpath and normcase all paths to help assure this. This can also handle the case where the env variable is a list instead of a string.

If delete_existing is False, a newpath element already in the path will not be moved to the end (it will be left where it is).

AppendUnique(delete_existing: bool = False, **kw) None[source]#

Append values to existing construction variables in an Environment, if they’re not already there. If delete_existing is True, removes existing values first, so values move to end.

Builder(**kw)[source]#
CacheDir(path, custom_class=None) None[source]#
Clean(targets, files) None[source]#
Clone(tools=[], toolpath=None, parse_flags=None, **kw)[source]#

Return a copy of a construction Environment.

The copy is like a Python “deep copy”–that is, independent copies are made recursively of each objects–except that a reference is copied when an object is not deep-copyable (like a function). There are no references to any mutable objects in the original Environment.

Command(target, source, action, **kw)[source]#

Builds the supplied target files from the supplied source files using the supplied action. Action may be any type that the Builder constructor will accept for an action.

Configure(*args, **kw)[source]#
Decider(function)[source]#
Depends(target, dependency)[source]#

Explicity specify that ‘target’s depend on ‘dependency’.

Detect(progs)[source]#

Return the first available program from one or more possibilities.

Parameters:

progs (str or list) – one or more command names to check for

Dictionary(*args)[source]#

Return construction variables from an environment.

Parameters:

*args (optional) – variable names to look up

Returns:

If args omitted, the dictionary of all construction variables. If one arg, the corresponding value is returned. If more than one arg, a list of values is returned.

Raises:

KeyError – if any of args is not in the construction environment.

Dir(name, *args, **kw)[source]#
Dump(key=None, format: str = 'pretty')[source]#

Return construction variables serialized to a string.

Parameters:
  • key (optional) – if None, format the whole dict of variables. Else format the value of key (Default value = None)

  • format (str, optional) – specify the format to serialize to. “pretty” generates a pretty-printed string, “json” a JSON-formatted string. (Default value = “pretty”)

Entry(name, *args, **kw)[source]#
Environment(**kw)[source]#
Execute(action, *args, **kw)[source]#

Directly execute an action through an Environment

File(name, *args, **kw)[source]#
FindFile(file, dirs)[source]#
FindInstalledFiles()[source]#

returns the list of all targets of the Install and InstallAs Builder.

FindIxes(paths, prefix, suffix)[source]#

Search a list of paths for something that matches the prefix and suffix.

Parameters:
  • paths – the list of paths or nodes.

  • prefix – construction variable for the prefix.

  • suffix – construction variable for the suffix.

Returns: the matched path or None

FindSourceFiles(node: str = '.') list[source]#

Return a list of all source files.

Flatten(sequence)[source]#
GetBuildPath(files)[source]#
Glob(pattern, ondisk: bool = True, source: bool = False, strings: bool = False, exclude=None)[source]#
Ignore(target, dependency)[source]#

Ignore a dependency.

Literal(string)[source]#
Local(*targets)[source]#
MergeFlags(args, unique: bool = True) None#

Merge flags into construction variables.

Merges the flags from args into this construction environent. If args is not a dict, it is first converted to one with flags distributed into appropriate construction variables. See ParseFlags().

As a side effect, if unique is true, a new object is created for each modified construction variable by the loop at the end. This is silently expected by the Override() parse_flags functionality, which does not want to share the list (or whatever) with the environment being overridden.

Parameters:
  • args – flags to merge

  • unique – merge flags rather than appending (default: True). When merging, path variables are retained from the front, other construction variables from the end.

NoCache(*targets)[source]#

Tags a target so that it will not be cached

NoClean(*targets)[source]#

Tags a target so that it will not be cleaned by -c

Override(overrides)#

Produce a modified environment whose variables are overridden by the overrides dictionaries. “overrides” is a dictionary that will override the variables of this environment.

This function is much more efficient than Clone() or creating a new Environment because it doesn’t copy the construction environment dictionary, it just wraps the underlying construction environment, and doesn’t even create a wrapper object if there are no overrides.

ParseConfig(command, function=None, unique: bool = True)[source]#

Parse the result of running a command to update construction vars.

Use function to parse the output of running command in order to modify the current environment.

Parameters:
  • command – a string or a list of strings representing a command and its arguments.

  • function – called to process the result of command, which will be passed as args. If function is omitted or None, MergeFlags() is used. Takes 3 args (env, args, unique)

  • unique – whether no duplicate values are allowed (default true)

ParseDepends(filename, must_exist=None, only_one: bool = False)[source]#

Parse a mkdep-style file for explicit dependencies. This is completely abusable, and should be unnecessary in the “normal” case of proper SCons configuration, but it may help make the transition from a Make hierarchy easier for some people to swallow. It can also be genuinely useful when using a tool that can write a .d file, but for which writing a scanner would be too complicated.

ParseFlags(*flags) dict#

Return a dict of parsed flags.

Parse flags and return a dict with the flags distributed into the appropriate construction variable names. The flags are treated as a typical set of command-line flags for a GNU-style toolchain, such as might have been generated by one of the {foo}-config scripts, and used to populate the entries based on knowledge embedded in this method - the choices are not expected to be portable to other toolchains.

If one of the flags strings begins with a bang (exclamation mark), it is assumed to be a command and the rest of the string is executed; the result of that evaluation is then added to the dict.

Platform(platform)[source]#
Precious(*targets)[source]#
Prepend(**kw) None[source]#

Prepend values to construction variables in an Environment.

The variable is created if it is not already present.

PrependENVPath(name, newpath, envname: str = 'ENV', sep=':', delete_existing: bool = True) None[source]#

Prepend path elements to the path name in the envname dictionary for this environment. Will only add any particular path once, and will normpath and normcase all paths to help assure this. This can also handle the case where the env variable is a list instead of a string.

If delete_existing is False, a newpath component already in the path will not be moved to the front (it will be left where it is).

PrependUnique(delete_existing: bool = False, **kw) None[source]#

Prepend values to existing construction variables in an Environment, if they’re not already there. If delete_existing is True, removes existing values first, so values move to front.

Pseudo(*targets)[source]#
PyPackageDir(modulename)[source]#
RemoveMethod(function) None#

Removes the specified function’s MethodWrapper from the added_methods list, so we don’t re-bind it when making a clone.

Replace(**kw) None[source]#

Replace existing construction variables in an Environment with new construction variables and/or values.

ReplaceIxes(path, old_prefix, old_suffix, new_prefix, new_suffix)[source]#

Replace old_prefix with new_prefix and old_suffix with new_suffix.

env - Environment used to interpolate variables. path - the path that will be modified. old_prefix - construction variable for the old prefix. old_suffix - construction variable for the old suffix. new_prefix - construction variable for the new prefix. new_suffix - construction variable for the new suffix.

Repository(*dirs, **kw) None[source]#
Requires(target, prerequisite)[source]#

Specify that ‘prerequisite’ must be built before ‘target’, (but ‘target’ does not actually depend on ‘prerequisite’ and need not be rebuilt if it changes).

SConsignFile(name='.sconsign', dbm_module=None) None[source]#
Scanner(*args, **kw)[source]#
SetDefault(**kw) None[source]#
SideEffect(side_effect, target)[source]#

Tell scons that side_effects are built as side effects of building targets.

Split(arg)[source]#

This function converts a string or list into a list of strings or Nodes. This makes things easier for users by allowing files to be specified as a white-space separated list to be split.

The input rules are:
  • A single string containing names separated by spaces. These will be split apart at the spaces.

  • A single Node instance

  • A list containing either strings or Node instances. Any strings in the list are not split at spaces.

In all cases, the function returns a list of Nodes and strings.

Tool(tool, toolpath=None, **kwargs) Tool[source]#

Find and run tool module tool.

Changed in version 4.2: returns the tool module rather than None.

Value(value, built_value=None, name=None)[source]#

Return a Value (Python expression) node.

Changed in version 4.0: the name parameter was added.

VariantDir(variant_dir, src_dir, duplicate: int = 1) None[source]#
WhereIs(prog, path=None, pathext=None, reject=None)[source]#

Find prog in the path.

_canonicalize(path)[source]#

Allow Dirs and strings beginning with # for top-relative.

Note this uses the current env’s fs (in self).

_changed_build(dependency, target, prev_ni, repo_node=None) bool[source]#
_changed_content(dependency, target, prev_ni, repo_node=None) bool[source]#
_changed_timestamp_match(dependency, target, prev_ni, repo_node=None) bool[source]#
_changed_timestamp_newer(dependency, target, prev_ni, repo_node=None) bool[source]#
_changed_timestamp_then_content(dependency, target, prev_ni, repo_node=None) bool[source]#
_find_toolpath_dir(tp)[source]#
_gsm()[source]#
_init_special() None#

Initial the dispatch tables for special handling of special construction variables.

_update(other) None[source]#

Private method to update an environment’s consvar dict directly.

Bypasses the normal checks that occur when users try to set items.

_update_onlynew(other) None[source]#

Private method to add new items to an environment’s consvar dict.

Only adds items from other whose keys do not already appear in the existing dict; values from other are not used for replacement. Bypasses the normal checks that occur when users try to set items.

arg2nodes(args, node_factory=<class 'SCons.Environment._Null'>, lookup_list=<class 'SCons.Environment._Null'>, **kw)#
backtick(command) str#

Emulate command substitution.

Provides behavior conceptually like POSIX Shell notation for running a command in backquotes (backticks) by running command and returning the resulting output string.

This is not really a public API any longer, it is provided for the use of ParseFlags() (which supports it using a syntax of !command) and ParseConfig().

Raises:

OSError – if the external command returned non-zero exit status.

get(key, default=None)#

Emulates the get() method of dictionaries.

get_CacheDir()[source]#
get_builder(name)[source]#

Fetch the builder with the specified name from the environment.

get_factory(factory, default: str = 'File')[source]#

Return a factory function for creating Nodes for this construction environment.

get_scanner(skey)[source]#

Find the appropriate scanner given a key (usually a file suffix).

gvars()#
items()#

Emulates the items() method of dictionaries.

keys()#

Emulates the keys() method of dictionaries.

lvars()#
scanner_map_delete(kw=None) None[source]#

Delete the cached scanner map (if we need to).

setdefault(key, default=None)#

Emulates the setdefault() method of dictionaries.

subst(string, raw: int = 0, target=None, source=None, conv=None, executor=None, overrides: dict | None = None)#

Recursively interpolates construction variables from the Environment into the specified string, returning the expanded result. Construction variables are specified by a $ prefix in the string and begin with an initial underscore or alphabetic character followed by any number of underscores or alphanumeric characters. The construction variable names may be surrounded by curly braces to separate the name from trailing characters.

subst_kw(kw, raw: int = 0, target=None, source=None)#
subst_list(string, raw: int = 0, target=None, source=None, conv=None, executor=None, overrides: dict | None = None)#

Calls through to SCons.Subst.scons_subst_list().

See the documentation for that function.

subst_path(path, target=None, source=None)#

Substitute a path list.

Turns EntryProxies into Nodes, leaving Nodes (and other objects) as-is.

subst_target_source(string, raw: int = 0, target=None, source=None, conv=None, executor=None, overrides: dict | None = None)#

Recursively interpolates construction variables from the Environment into the specified string, returning the expanded result. Construction variables are specified by a $ prefix in the string and begin with an initial underscore or alphabetic character followed by any number of underscores or alphanumeric characters. The construction variable names may be surrounded by curly braces to separate the name from trailing characters.

validate_CacheDir_class(custom_class=None)[source]#

Validate the passed custom CacheDir class, or if no args are passed, validate the custom CacheDir class from the environment.

values()#

Emulates the values() method of dictionaries.

class SCons.Environment.BuilderDict(mapping, env)[source]#

Bases: UserDict

This is a dictionary-like class used by an Environment to hold the Builders. We need to do this because every time someone changes the Builders in the Environment’s BUILDERS dictionary, we must update the Environment’s attributes.

_abc_impl = <_abc._abc_data object>#
clear() None.  Remove all items from D.#
copy()#
classmethod fromkeys(iterable, value=None)#
get(k[, d]) D[k] if k in D, else d.  d defaults to None.#
items() a set-like object providing a view on D's items#
keys() a set-like object providing a view on D's keys#
pop(k[, d]) v, remove specified key and return the corresponding value.#

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() (k, v), remove and return some (key, value) pair#

as a 2-tuple; but raise KeyError if D is empty.

setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D#
update([E, ]**F) None.  Update D from mapping/iterable E and F.[source]#

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values() an object providing a view on D's values#
class SCons.Environment.BuilderWrapper(obj: Any, method: Callable, name: str | None = None)[source]#

Bases: MethodWrapper

A MethodWrapper subclass that that associates an environment with a Builder.

This mainly exists to wrap the __call__() function so that all calls to Builders can have their argument lists massaged in the same way (treat a lone argument as the source, treat two arguments as target then source, make sure both target and source are lists) without having to have cut-and-paste code to do it.

As a bit of obsessive backwards compatibility, we also intercept attempts to get or set the “env” or “builder” attributes, which were the names we used before we put the common functionality into the MethodWrapper base class. We’ll keep this around for a while in case people shipped Tool modules that reached into the wrapper (like the Tool/qt.py module does, or did). There shouldn’t be a lot attribute fetching or setting on these, so a little extra work shouldn’t hurt.

clone(new_object)#

Returns an object that re-binds the underlying “method” to the specified new object.

SCons.Environment.NoSubstitutionProxy(subject)[source]#

An entry point for returning a proxy subclass instance that overrides the subst*() methods so they don’t actually perform construction variable substitution. This is specifically intended to be the shim layer in between global function calls (which don’t want construction variable substitution) and the DefaultEnvironment() (which would substitute variables if left to its own devices).

We have to wrap this in a function that allows us to delay definition of the class until it’s necessary, so that when it subclasses Environment it will pick up whatever Environment subclass the wrapper interface might have assigned to SCons.Environment.Environment.

class SCons.Environment.OverrideEnvironment(subject, overrides=None)[source]#

Bases: Base

A proxy that overrides variables in a wrapped construction environment by returning values from an overrides dictionary in preference to values from the underlying subject environment.

This is a lightweight (I hope) proxy that passes through most use of attributes to the underlying Environment.Base class, but has just enough additional methods defined to act like a real construction environment with overridden values. It can wrap either a Base construction environment, or another OverrideEnvironment, which can in turn nest arbitrary OverrideEnvironments…

Note that we do not call the underlying base class (SubsitutionEnvironment) initialization, because we get most of those from proxying the attributes of the subject construction environment. But because we subclass SubstitutionEnvironment, this class also has inherited arg2nodes() and subst*() methods; those methods can’t be proxied because they need this object’s methods to fetch the values from the overrides dictionary.

Action(*args, **kw)#
AddMethod(function, name=None) None#

Adds the specified function as a method of this construction environment with the specified name. If the name is omitted, the default name is the name of the function itself.

AddPostAction(files, action)#
AddPreAction(files, action)#
Alias(target, source=[], action=None, **kw)#
AlwaysBuild(*targets)#
Append(**kw) None#

Append values to construction variables in an Environment.

The variable is created if it is not already present.

AppendENVPath(name, newpath, envname: str = 'ENV', sep=':', delete_existing: bool = False) None#

Append path elements to the path name in the envname dictionary for this environment. Will only add any particular path once, and will normpath and normcase all paths to help assure this. This can also handle the case where the env variable is a list instead of a string.

If delete_existing is False, a newpath element already in the path will not be moved to the end (it will be left where it is).

AppendUnique(delete_existing: bool = False, **kw) None#

Append values to existing construction variables in an Environment, if they’re not already there. If delete_existing is True, removes existing values first, so values move to end.

Builder(**kw)#
CacheDir(path, custom_class=None) None#
Clean(targets, files) None#
Clone(tools=[], toolpath=None, parse_flags=None, **kw)#

Return a copy of a construction Environment.

The copy is like a Python “deep copy”–that is, independent copies are made recursively of each objects–except that a reference is copied when an object is not deep-copyable (like a function). There are no references to any mutable objects in the original Environment.

Command(target, source, action, **kw)#

Builds the supplied target files from the supplied source files using the supplied action. Action may be any type that the Builder constructor will accept for an action.

Configure(*args, **kw)#
Decider(function)#
Depends(target, dependency)#

Explicity specify that ‘target’s depend on ‘dependency’.

Detect(progs)#

Return the first available program from one or more possibilities.

Parameters:

progs (str or list) – one or more command names to check for

Dictionary(*args)[source]#

Return construction variables from an environment.

Parameters:

*args (optional) – variable names to look up

Returns:

If args omitted, the dictionary of all construction variables. If one arg, the corresponding value is returned. If more than one arg, a list of values is returned.

Raises:

KeyError – if any of args is not in the construction environment.

Dir(name, *args, **kw)#
Dump(key=None, format: str = 'pretty')#

Return construction variables serialized to a string.

Parameters:
  • key (optional) – if None, format the whole dict of variables. Else format the value of key (Default value = None)

  • format (str, optional) – specify the format to serialize to. “pretty” generates a pretty-printed string, “json” a JSON-formatted string. (Default value = “pretty”)

Entry(name, *args, **kw)#
Environment(**kw)#
Execute(action, *args, **kw)#

Directly execute an action through an Environment

File(name, *args, **kw)#
FindFile(file, dirs)#
FindInstalledFiles()#

returns the list of all targets of the Install and InstallAs Builder.

FindIxes(paths, prefix, suffix)#

Search a list of paths for something that matches the prefix and suffix.

Parameters:
  • paths – the list of paths or nodes.

  • prefix – construction variable for the prefix.

  • suffix – construction variable for the suffix.

Returns: the matched path or None

FindSourceFiles(node: str = '.') list#

Return a list of all source files.

Flatten(sequence)#
GetBuildPath(files)#
Glob(pattern, ondisk: bool = True, source: bool = False, strings: bool = False, exclude=None)#
Ignore(target, dependency)#

Ignore a dependency.

Literal(string)#
Local(*targets)#
MergeFlags(args, unique: bool = True) None#

Merge flags into construction variables.

Merges the flags from args into this construction environent. If args is not a dict, it is first converted to one with flags distributed into appropriate construction variables. See ParseFlags().

As a side effect, if unique is true, a new object is created for each modified construction variable by the loop at the end. This is silently expected by the Override() parse_flags functionality, which does not want to share the list (or whatever) with the environment being overridden.

Parameters:
  • args – flags to merge

  • unique – merge flags rather than appending (default: True). When merging, path variables are retained from the front, other construction variables from the end.

NoCache(*targets)#

Tags a target so that it will not be cached

NoClean(*targets)#

Tags a target so that it will not be cleaned by -c

Override(overrides)#

Produce a modified environment whose variables are overridden by the overrides dictionaries. “overrides” is a dictionary that will override the variables of this environment.

This function is much more efficient than Clone() or creating a new Environment because it doesn’t copy the construction environment dictionary, it just wraps the underlying construction environment, and doesn’t even create a wrapper object if there are no overrides.

ParseConfig(command, function=None, unique: bool = True)#

Parse the result of running a command to update construction vars.

Use function to parse the output of running command in order to modify the current environment.

Parameters:
  • command – a string or a list of strings representing a command and its arguments.

  • function – called to process the result of command, which will be passed as args. If function is omitted or None, MergeFlags() is used. Takes 3 args (env, args, unique)

  • unique – whether no duplicate values are allowed (default true)

ParseDepends(filename, must_exist=None, only_one: bool = False)#

Parse a mkdep-style file for explicit dependencies. This is completely abusable, and should be unnecessary in the “normal” case of proper SCons configuration, but it may help make the transition from a Make hierarchy easier for some people to swallow. It can also be genuinely useful when using a tool that can write a .d file, but for which writing a scanner would be too complicated.

ParseFlags(*flags) dict#

Return a dict of parsed flags.

Parse flags and return a dict with the flags distributed into the appropriate construction variable names. The flags are treated as a typical set of command-line flags for a GNU-style toolchain, such as might have been generated by one of the {foo}-config scripts, and used to populate the entries based on knowledge embedded in this method - the choices are not expected to be portable to other toolchains.

If one of the flags strings begins with a bang (exclamation mark), it is assumed to be a command and the rest of the string is executed; the result of that evaluation is then added to the dict.

Platform(platform)#
Precious(*targets)#
Prepend(**kw) None#

Prepend values to construction variables in an Environment.

The variable is created if it is not already present.

PrependENVPath(name, newpath, envname: str = 'ENV', sep=':', delete_existing: bool = True) None#

Prepend path elements to the path name in the envname dictionary for this environment. Will only add any particular path once, and will normpath and normcase all paths to help assure this. This can also handle the case where the env variable is a list instead of a string.

If delete_existing is False, a newpath component already in the path will not be moved to the front (it will be left where it is).

PrependUnique(delete_existing: bool = False, **kw) None#

Prepend values to existing construction variables in an Environment, if they’re not already there. If delete_existing is True, removes existing values first, so values move to front.

Pseudo(*targets)#
PyPackageDir(modulename)#
RemoveMethod(function) None#

Removes the specified function’s MethodWrapper from the added_methods list, so we don’t re-bind it when making a clone.

Replace(**kw) None[source]#

Replace existing construction variables in an Environment with new construction variables and/or values.

ReplaceIxes(path, old_prefix, old_suffix, new_prefix, new_suffix)#

Replace old_prefix with new_prefix and old_suffix with new_suffix.

env - Environment used to interpolate variables. path - the path that will be modified. old_prefix - construction variable for the old prefix. old_suffix - construction variable for the old suffix. new_prefix - construction variable for the new prefix. new_suffix - construction variable for the new suffix.

Repository(*dirs, **kw) None#
Requires(target, prerequisite)#

Specify that ‘prerequisite’ must be built before ‘target’, (but ‘target’ does not actually depend on ‘prerequisite’ and need not be rebuilt if it changes).

SConsignFile(name='.sconsign', dbm_module=None) None#
Scanner(*args, **kw)#
SetDefault(**kw) None#
SideEffect(side_effect, target)#

Tell scons that side_effects are built as side effects of building targets.

Split(arg)#

This function converts a string or list into a list of strings or Nodes. This makes things easier for users by allowing files to be specified as a white-space separated list to be split.

The input rules are:
  • A single string containing names separated by spaces. These will be split apart at the spaces.

  • A single Node instance

  • A list containing either strings or Node instances. Any strings in the list are not split at spaces.

In all cases, the function returns a list of Nodes and strings.

Tool(tool, toolpath=None, **kwargs) Tool#

Find and run tool module tool.

Changed in version 4.2: returns the tool module rather than None.

Value(value, built_value=None, name=None)#

Return a Value (Python expression) node.

Changed in version 4.0: the name parameter was added.

VariantDir(variant_dir, src_dir, duplicate: int = 1) None#
WhereIs(prog, path=None, pathext=None, reject=None)#

Find prog in the path.

_canonicalize(path)#

Allow Dirs and strings beginning with # for top-relative.

Note this uses the current env’s fs (in self).

_changed_build(dependency, target, prev_ni, repo_node=None) bool#
_changed_content(dependency, target, prev_ni, repo_node=None) bool#
_changed_timestamp_match(dependency, target, prev_ni, repo_node=None) bool#
_changed_timestamp_newer(dependency, target, prev_ni, repo_node=None) bool#
_changed_timestamp_then_content(dependency, target, prev_ni, repo_node=None) bool#
_find_toolpath_dir(tp)#
_gsm()#
_init_special() None#

Initial the dispatch tables for special handling of special construction variables.

_update(other) None[source]#

Private method to update an environment’s consvar dict directly.

Bypasses the normal checks that occur when users try to set items.

_update_onlynew(other) None[source]#

Update a dict with new keys.

Unlike the .update method, if the key is already present, it is not replaced.

arg2nodes(args, node_factory=<class 'SCons.Environment._Null'>, lookup_list=<class 'SCons.Environment._Null'>, **kw)#
backtick(command) str#

Emulate command substitution.

Provides behavior conceptually like POSIX Shell notation for running a command in backquotes (backticks) by running command and returning the resulting output string.

This is not really a public API any longer, it is provided for the use of ParseFlags() (which supports it using a syntax of !command) and ParseConfig().

Raises:

OSError – if the external command returned non-zero exit status.

get(key, default=None)[source]#

Emulates the get() method of dictionaries.

get_CacheDir()#
get_builder(name)#

Fetch the builder with the specified name from the environment.

get_factory(factory, default: str = 'File')#

Return a factory function for creating Nodes for this construction environment.

get_scanner(skey)#

Find the appropriate scanner given a key (usually a file suffix).

gvars()[source]#
items()[source]#

Emulates the items() method of dictionaries.

keys()[source]#

Emulates the keys() method of dictionaries.

lvars()[source]#
scanner_map_delete(kw=None) None#

Delete the cached scanner map (if we need to).

setdefault(key, default=None)[source]#

Emulates the setdefault() method of dictionaries.

subst(string, raw: int = 0, target=None, source=None, conv=None, executor=None, overrides: dict | None = None)#

Recursively interpolates construction variables from the Environment into the specified string, returning the expanded result. Construction variables are specified by a $ prefix in the string and begin with an initial underscore or alphabetic character followed by any number of underscores or alphanumeric characters. The construction variable names may be surrounded by curly braces to separate the name from trailing characters.

subst_kw(kw, raw: int = 0, target=None, source=None)#
subst_list(string, raw: int = 0, target=None, source=None, conv=None, executor=None, overrides: dict | None = None)#

Calls through to SCons.Subst.scons_subst_list().

See the documentation for that function.

subst_path(path, target=None, source=None)#

Substitute a path list.

Turns EntryProxies into Nodes, leaving Nodes (and other objects) as-is.

subst_target_source(string, raw: int = 0, target=None, source=None, conv=None, executor=None, overrides: dict | None = None)#

Recursively interpolates construction variables from the Environment into the specified string, returning the expanded result. Construction variables are specified by a $ prefix in the string and begin with an initial underscore or alphabetic character followed by any number of underscores or alphanumeric characters. The construction variable names may be surrounded by curly braces to separate the name from trailing characters.

validate_CacheDir_class(custom_class=None)#

Validate the passed custom CacheDir class, or if no args are passed, validate the custom CacheDir class from the environment.

values()[source]#

Emulates the values() method of dictionaries.

class SCons.Environment.SubstitutionEnvironment(**kw)[source]#

Bases: object

Base class for different flavors of construction environments.

This class contains a minimal set of methods that handle construction variable expansion and conversion of strings to Nodes, which may or may not be actually useful as a stand-alone class. Which methods ended up in this class is pretty arbitrary right now. They’re basically the ones which we’ve empirically determined are common to the different construction environment subclasses, and most of the others that use or touch the underlying dictionary of construction variables.

Eventually, this class should contain all the methods that we determine are necessary for a “minimal” interface to the build engine. A full “native Python” SCons environment has gotten pretty heavyweight with all of the methods and Tools and construction variables we’ve jammed in there, so it would be nice to have a lighter weight alternative for interfaces that don’t need all of the bells and whistles. (At some point, we’ll also probably rename this class “Base,” since that more reflects what we want this class to become, but because we’ve released comments that tell people to subclass Environment.Base to create their own flavors of construction environment, we’ll save that for a future refactoring when this class actually becomes useful.)

AddMethod(function, name=None) None[source]#

Adds the specified function as a method of this construction environment with the specified name. If the name is omitted, the default name is the name of the function itself.

MergeFlags(args, unique: bool = True) None[source]#

Merge flags into construction variables.

Merges the flags from args into this construction environent. If args is not a dict, it is first converted to one with flags distributed into appropriate construction variables. See ParseFlags().

As a side effect, if unique is true, a new object is created for each modified construction variable by the loop at the end. This is silently expected by the Override() parse_flags functionality, which does not want to share the list (or whatever) with the environment being overridden.

Parameters:
  • args – flags to merge

  • unique – merge flags rather than appending (default: True). When merging, path variables are retained from the front, other construction variables from the end.

Override(overrides)[source]#

Produce a modified environment whose variables are overridden by the overrides dictionaries. “overrides” is a dictionary that will override the variables of this environment.

This function is much more efficient than Clone() or creating a new Environment because it doesn’t copy the construction environment dictionary, it just wraps the underlying construction environment, and doesn’t even create a wrapper object if there are no overrides.

ParseFlags(*flags) dict[source]#

Return a dict of parsed flags.

Parse flags and return a dict with the flags distributed into the appropriate construction variable names. The flags are treated as a typical set of command-line flags for a GNU-style toolchain, such as might have been generated by one of the {foo}-config scripts, and used to populate the entries based on knowledge embedded in this method - the choices are not expected to be portable to other toolchains.

If one of the flags strings begins with a bang (exclamation mark), it is assumed to be a command and the rest of the string is executed; the result of that evaluation is then added to the dict.

RemoveMethod(function) None[source]#

Removes the specified function’s MethodWrapper from the added_methods list, so we don’t re-bind it when making a clone.

_init_special() None[source]#

Initial the dispatch tables for special handling of special construction variables.

arg2nodes(args, node_factory=<class 'SCons.Environment._Null'>, lookup_list=<class 'SCons.Environment._Null'>, **kw)[source]#
backtick(command) str[source]#

Emulate command substitution.

Provides behavior conceptually like POSIX Shell notation for running a command in backquotes (backticks) by running command and returning the resulting output string.

This is not really a public API any longer, it is provided for the use of ParseFlags() (which supports it using a syntax of !command) and ParseConfig().

Raises:

OSError – if the external command returned non-zero exit status.

get(key, default=None)[source]#

Emulates the get() method of dictionaries.

gvars()[source]#
items()[source]#

Emulates the items() method of dictionaries.

keys()[source]#

Emulates the keys() method of dictionaries.

lvars()[source]#
setdefault(key, default=None)[source]#

Emulates the setdefault() method of dictionaries.

subst(string, raw: int = 0, target=None, source=None, conv=None, executor=None, overrides: dict | None = None)[source]#

Recursively interpolates construction variables from the Environment into the specified string, returning the expanded result. Construction variables are specified by a $ prefix in the string and begin with an initial underscore or alphabetic character followed by any number of underscores or alphanumeric characters. The construction variable names may be surrounded by curly braces to separate the name from trailing characters.

subst_kw(kw, raw: int = 0, target=None, source=None)[source]#
subst_list(string, raw: int = 0, target=None, source=None, conv=None, executor=None, overrides: dict | None = None)[source]#

Calls through to SCons.Subst.scons_subst_list().

See the documentation for that function.

subst_path(path, target=None, source=None)[source]#

Substitute a path list.

Turns EntryProxies into Nodes, leaving Nodes (and other objects) as-is.

subst_target_source(string, raw: int = 0, target=None, source=None, conv=None, executor=None, overrides: dict | None = None)#

Recursively interpolates construction variables from the Environment into the specified string, returning the expanded result. Construction variables are specified by a $ prefix in the string and begin with an initial underscore or alphabetic character followed by any number of underscores or alphanumeric characters. The construction variable names may be surrounded by curly braces to separate the name from trailing characters.

values()[source]#

Emulates the values() method of dictionaries.

class SCons.Environment._Null[source]#

Bases: object

SCons.Environment._add_cppdefines(env_dict: dict, val, prepend: bool = False, unique: bool = False, delete_existing: bool = False) None[source]#

Adds to CPPDEFINES, using the rules for C preprocessor macros.

This is split out from regular construction variable addition because these entries can express either a macro with a replacement value or one without. A macro with replacement value can be supplied as val in three ways: as a combined string "name=value"; as a tuple (name, value), or as an entry in a dictionary {"name": value}. A list argument with multiple macros can also be given.

Additions can be unconditional (duplicates allowed) or uniquing (no dupes).

Note if a replacement value is supplied, unique requires a full match to decide uniqueness - both the macro name and the replacement. The inner _is_in() is used to figure that out.

Parameters:
  • env_dict – the dictionary containing the CPPDEFINES to be modified.

  • val – the value to add, can be string, sequence or dict

  • prepend – whether to put val in front or back.

  • unique – whether to add val if it already exists.

  • delete_existing – if unique is true, add val after removing previous.

New in version 4.5.0.

SCons.Environment._del_SCANNERS(env, key) None[source]#
SCons.Environment._delete_duplicates(l, keep_last)[source]#

Delete duplicates from a sequence, keeping the first or last.

SCons.Environment._null#

alias of _Null

SCons.Environment._set_BUILDERS(env, key, value)[source]#
SCons.Environment._set_SCANNERS(env, key, value) None[source]#
SCons.Environment._set_future_reserved(env, key, value) None[source]#
SCons.Environment._set_reserved(env, key, value) None[source]#
SCons.Environment.alias_builder(env, target, source) None[source]#
SCons.Environment.apply_tools(env, tools, toolpath) None[source]#
SCons.Environment.copy_non_reserved_keywords(dict)[source]#
SCons.Environment.default_copy_from_cache(env, src, dst)[source]#
SCons.Environment.default_copy_to_cache(env, src, dst)[source]#
SCons.Environment.default_decide_source(dependency, target, prev_ni, repo_node=None)[source]#
SCons.Environment.default_decide_target(dependency, target, prev_ni, repo_node=None)[source]#
SCons.Environment.is_valid_construction_var(varstr) bool[source]#

Return True if varstr is a legitimate construction variable.

SCons.Errors module#

SCons exception classes.

Used to handle internal and user errors in SCons.

exception SCons.Errors.BuildError(node=None, errstr: str = 'Unknown error', status: int = 2, exitstatus: int = 2, filename=None, executor=None, action=None, command=None, exc_info=(None, None, None))[source]#

Bases: Exception

SCons Errors that can occur while building.

A BuildError exception contains information both about the erorr itself, and what caused the error.

Variables:
  • node – (cause) the error occurred while building this target node(s)

  • errstr – (info) a description of the error message

  • status – (info) the return code of the action that caused the build error. Must be set to a non-zero value even if the build error is not due to an action returning a non-zero returned code.

  • exitstatus – (info) SCons exit status due to this build error. Must be nonzero unless due to an explicit Exit() call. Not always the same as status, since actions return a status code that should be respected, but SCons typically exits with 2 irrespective of the return value of the failed action.

  • filename – (info) The name of the file or directory that caused the build error. Set to None if no files are associated with this error. This might be different from the target being built. For example, failure to create the directory in which the target file will appear. It can be None if the error is not due to a particular filename.

  • executor – (cause) the executor that caused the build to fail (might be None if the build failures is not due to the executor failing)

  • action – (cause) the action that caused the build to fail (might be None if the build failures is not due to the an action failure)

  • command – (cause) the command line for the action that caused the build to fail (might be None if the build failures is not due to the an action failure)

  • exc_info – (info) Info about exception that caused the build error. Set to (None, None, None) if this build error is not due to an exception.

exception SCons.Errors.ExplicitExit(node=None, status=None, *args)[source]#

Bases: Exception

exception SCons.Errors.InternalError[source]#

Bases: Exception

exception SCons.Errors.MSVCError[source]#

Bases: OSError

exception SCons.Errors.SConsEnvironmentError[source]#

Bases: Exception

exception SCons.Errors.StopError[source]#

Bases: Exception

exception SCons.Errors.UserError[source]#

Bases: Exception

SCons.Errors.convert_to_BuildError(status, exc_info=None)[source]#

Convert a return code to a BuildError Exception.

The buildError.status we set here will normally be used as the exit status of the “scons” process.

Parameters:
  • status – can either be a return code or an Exception.

  • exc_info (tuple, optional) – explicit exception information.

SCons.Executor module#

Execute actions with specific lists of target and source Nodes.

SCons.Executor.AddBatchExecutor(key, executor) None[source]#
class SCons.Executor.Batch(targets=[], sources=[])[source]#

Bases: object

Remembers exact association between targets and sources of executor.

sources#
targets#
class SCons.Executor.Executor(action, env=None, overridelist=[{}], targets=[], sources=[], builder_kw={})[source]#

Bases: object

A class for controlling instances of executing an action.

This largely exists to hold a single association of an action, environment, list of environment override dictionaries, targets and sources for later processing as needed.

_changed_sources_list#
_changed_targets_list#
_do_execute#
_execute_str#
_get_changed_sources(*args, **kw)[source]#
_get_changed_targets(*args, **kw)[source]#
_get_changes() None[source]#
_get_source(*args, **kw)[source]#
_get_sources(*args, **kw)[source]#
_get_target(*args, **kw)[source]#
_get_targets(*args, **kw)[source]#
_get_unchanged_sources(*args, **kw)[source]#
_get_unchanged_targets(*args, **kw)[source]#
_get_unignored_sources_key(node, ignore=())[source]#
_memo#
_unchanged_sources_list#
_unchanged_targets_list#
action_list#
add_batch(targets, sources) None[source]#

Add pair of associated target and source to this Executor’s list. This is necessary for “batch” Builders that can be called repeatedly to build up a list of matching target and source files that will be used in order to update multiple target files at once from multiple corresponding source files, for tools like MSVC that support it.

add_post_action(action) None[source]#
add_pre_action(action) None[source]#
add_sources(sources) None[source]#

Add source files to this Executor’s list. This is necessary for “multi” Builders that can be called repeatedly to build up a source file list for a given target.

batches#
builder_kw#
cleanup() None[source]#
env#
get_action_list()[source]#
get_action_side_effects()[source]#

Returns all side effects for all batches of this Executor used by the underlying Action.

get_action_targets()[source]#
get_all_children()[source]#

Returns all unique children (dependencies) for all batches of this Executor.

The Taskmaster can recognize when it’s already evaluated a Node, so we don’t have to make this list unique for its intended canonical use case, but we expect there to be a lot of redundancy (long lists of batched .cc files #including the same .h files over and over), so removing the duplicates once up front should save the Taskmaster a lot of work.

get_all_prerequisites()[source]#

Returns all unique (order-only) prerequisites for all batches of this Executor.

get_all_sources()[source]#

Returns all sources for all batches of this Executor.

get_all_targets()[source]#

Returns all targets for all batches of this Executor.

get_build_env()[source]#

Fetch or create the appropriate build Environment for this Executor.

get_build_scanner_path(scanner)[source]#

Fetch the scanner path for this executor’s targets and sources.

get_contents()[source]#

Fetch the signature contents. This is the main reason this class exists, so we can compute this once and cache it regardless of how many target or source Nodes there are.

Returns bytes

get_implicit_deps()[source]#

Return the executor’s implicit dependencies, i.e. the nodes of the commands to be executed.

get_kw(kw={})[source]#
get_lvars()[source]#
get_sources()[source]#
get_timestamp() int[source]#

Fetch a time stamp for this Executor. We don’t have one, of course (only files do), but this is the interface used by the timestamp module.

get_unignored_sources(node, ignore=())[source]#
lvars#
nullify() None[source]#
overridelist#
post_actions#
pre_actions#
prepare()[source]#

Preparatory checks for whether this Executor can go ahead and (try to) build its targets.

scan(scanner, node_list) None[source]#

Scan a list of this Executor’s files (targets or sources) for implicit dependencies and update all of the targets with them. This essentially short-circuits an N*M scan of the sources for each individual target, which is a hell of a lot more efficient.

scan_sources(scanner) None[source]#
scan_targets(scanner) None[source]#
set_action_list(action)[source]#
SCons.Executor.GetBatchExecutor(key)[source]#
class SCons.Executor.Null(*args, **kw)[source]#

Bases: object

A null Executor, with a null build Environment, that does nothing when the rest of the methods call it.

This might be able to disappear when we refactor things to disassociate Builders from Nodes entirely, so we’re not going to worry about unit tests for this–at least for now.

_changed_sources_list#
_changed_targets_list#
_do_execute#
_execute_str#
_memo#
_morph() None[source]#

Morph this Null executor to a real Executor object.

_unchanged_sources_list#
_unchanged_targets_list#
action_list#
add_post_action(action) None[source]#
add_pre_action(action) None[source]#
batches#
builder_kw#
cleanup() None[source]#
env#
get_action_list()[source]#
get_action_side_effects()[source]#
get_action_targets()[source]#
get_all_children()[source]#
get_all_prerequisites()[source]#
get_all_sources()[source]#
get_all_targets()[source]#
get_build_env()[source]#
get_build_scanner_path()[source]#
get_contents() str[source]#
get_unignored_sources(*args, **kw)[source]#
lvars#
overridelist#
post_actions#
pre_actions#
prepare() None[source]#
set_action_list(action) None[source]#
class SCons.Executor.NullEnvironment(*args, **kwargs)[source]#

Bases: Null

SCons = <module 'SCons' from '/Users/bdbaddog/devel/scons/git/as_scons/SCons/__init__.py'>#
_CacheDir = <SCons.CacheDir.CacheDir object>#
_CacheDir_path = None#
get_CacheDir()[source]#
class SCons.Executor.TSList(func)[source]#

Bases: UserList

A class that implements $TARGETS or $SOURCES expansions by wrapping an executor Method. This class is used in the Executor.lvars() to delay creation of NodeList objects until they’re needed.

Note that we subclass collections.UserList purely so that the is_Sequence() function will identify an object of this class as a list during variable expansion. We’re not really using any collections.UserList methods in practice.

_abc_impl = <_abc._abc_data object>#
append(item)#

S.append(value) – append value to the end of the sequence

clear() None -- remove all items from S#
copy()#
count(value) integer -- return number of occurrences of value#
extend(other)#

S.extend(iterable) – extend sequence by appending elements from the iterable

index(value[, start[, stop]]) integer -- return first index of value.#

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

insert(i, item)#

S.insert(index, value) – insert value before index

pop([index]) item -- remove and return item at index (default last).#

Raise IndexError if list is empty or index is out of range.

remove(item)#

S.remove(value) – remove first occurrence of value. Raise ValueError if the value is not present.

reverse()#

S.reverse() – reverse IN PLACE

sort(*args, **kwds)#
class SCons.Executor.TSObject(func)[source]#

Bases: object

A class that implements $TARGET or $SOURCE expansions by wrapping an Executor method.

SCons.Executor.execute_action_list(obj, target, kw)[source]#

Actually execute the action list.

SCons.Executor.execute_actions_str(obj)[source]#
SCons.Executor.execute_nothing(obj, target, kw) int[source]#
SCons.Executor.execute_null_str(obj) str[source]#
SCons.Executor.get_NullEnvironment()[source]#

Use singleton pattern for Null Environments.

SCons.Executor.rfile(node)[source]#

A function to return the results of a Node’s rfile() method, if it exists, and the Node itself otherwise (if it’s a Value Node, e.g.).

SCons.Memoize module#

Decorator-based memoizer to count caching stats.

A decorator-based implementation to count hits and misses of the computed values that various methods cache in memory.

Use of this modules assumes that wrapped methods be coded to cache their values in a consistent way. In particular, it requires that the class uses a dictionary named “_memo” to store the cached values.

Here is an example of wrapping a method that returns a computed value, with no input parameters:

@SCons.Memoize.CountMethodCall
def foo(self):

    try:                                                    # Memoization
        return self._memo['foo']                            # Memoization
    except KeyError:                                        # Memoization
        pass                                                # Memoization

    result = self.compute_foo_value()

    self._memo['foo'] = result                              # Memoization

    return result

Here is an example of wrapping a method that will return different values based on one or more input arguments:

def _bar_key(self, argument):                               # Memoization
    return argument                                         # Memoization

@SCons.Memoize.CountDictCall(_bar_key)
def bar(self, argument):

    memo_key = argument                                     # Memoization
    try:                                                    # Memoization
        memo_dict = self._memo['bar']                       # Memoization
    except KeyError:                                        # Memoization
        memo_dict = {}                                      # Memoization
        self._memo['dict'] = memo_dict                      # Memoization
    else:                                                   # Memoization
        try:                                                # Memoization
            return memo_dict[memo_key]                      # Memoization
        except KeyError:                                    # Memoization
            pass                                            # Memoization

    result = self.compute_bar_value(argument)

    memo_dict[memo_key] = result                            # Memoization

    return result

Deciding what to cache is tricky, because different configurations can have radically different performance tradeoffs, and because the tradeoffs involved are often so non-obvious. Consequently, deciding whether or not to cache a given method will likely be more of an art than a science, but should still be based on available data from this module. Here are some VERY GENERAL guidelines about deciding whether or not to cache return values from a method that’s being called a lot:

– The first question to ask is, “Can we change the calling code

so this method isn’t called so often?” Sometimes this can be done by changing the algorithm. Sometimes the caller should be memoized, not the method you’re looking at.

—The memoized function should be timed with multiple configurations to make sure it doesn’t inadvertently slow down some other configuration.

– When memoizing values based on a dictionary key composed of

input arguments, you don’t need to use all of the arguments if some of them don’t affect the return values.

class SCons.Memoize.CountDict(cls_name, method_name, keymaker)[source]#

Bases: Counter

A counter class for memoized values stored in a dictionary, with keys based on the method’s input arguments.

A CountDict object is instantiated in a decorator for each of the class’s methods that memoizes its return value in a dictionary, indexed by some key that can be computed from one or more of its input arguments.

count(*args, **kw) None[source]#

Counts whether the computed key value is already present in the memoization dictionary (a hit) or not (a miss).

display() None#
key()#
SCons.Memoize.CountDictCall(keyfunc)[source]#

Decorator for counting memoizer hits/misses while accessing dictionary values with a key-generating function. Like CountMethodCall above, it wraps the given method fn and uses a CountDict object to keep track of the caching statistics. The dict-key function keyfunc has to get passed in the decorator call and gets stored in the CountDict instance. Wrapping gets enabled by calling EnableMemoization().

SCons.Memoize.CountMethodCall(fn)[source]#

Decorator for counting memoizer hits/misses while retrieving a simple value in a class method. It wraps the given method fn and uses a CountValue object to keep track of the caching statistics. Wrapping gets enabled by calling EnableMemoization().

class SCons.Memoize.CountValue(cls_name, method_name)[source]#

Bases: Counter

A counter class for simple, atomic memoized values.

A CountValue object should be instantiated in a decorator for each of the class’s methods that memoizes its return value by simply storing the return value in its _memo dictionary.

count(*args, **kw) None[source]#

Counts whether the memoized value has already been set (a hit) or not (a miss).

display() None#
key()#
class SCons.Memoize.Counter(cls_name, method_name)[source]#

Bases: object

Base class for counting memoization hits and misses.

We expect that the initialization in a matching decorator will fill in the correct class name and method name that represents the name of the function being counted.

display() None[source]#
key()[source]#
SCons.Memoize.Dump(title=None) None[source]#

Dump the hit/miss count for all the counters collected so far.

SCons.Memoize.EnableMemoization() None[source]#

SCons.PathList module#

Handle lists of directory paths.

These are the path lists that get set as CPPPATH, LIBPATH, etc.) with as much caching of data and efficiency as we can, while still keeping the evaluation delayed so that we Do the Right Thing (almost) regardless of how the variable is specified.

SCons.PathList.PathList(pathlist, split=True)#

Returns the cached _PathList object for the specified pathlist, creating and caching a new object as necessary.

class SCons.PathList._PathList(pathlist, split=True)[source]#

Bases: object

An actual PathList object.

subst_path(env, target, source)[source]#

Performs construction variable substitution on a pre-digested PathList for a specific target and source.

SCons.PathList.node_conv(obj)[source]#

This is the “string conversion” routine that we have our substitutions use to return Nodes, not strings. This relies on the fact that an EntryProxy object has a get() method that returns the underlying Node that it wraps, which is a bit of architectural dependence that we might need to break or modify in the future in response to additional requirements.

SCons.SConf module#

Autoconf-like configuration support.

In other words, SConf allows to run tests on the build machine to detect capabilities of system and do some things based on result: generate config files, header files for C/C++, update variables in environment.

Tests on the build system can detect if compiler sees header files, if libraries are installed, if some command line options are supported etc.

SCons.SConf.CheckCC(context) bool[source]#
SCons.SConf.CheckCHeader(context, header, include_quotes: str = '""')[source]#

A test for a C header file.

SCons.SConf.CheckCXX(context) bool[source]#
SCons.SConf.CheckCXXHeader(context, header, include_quotes: str = '""')[source]#

A test for a C++ header file.

class SCons.SConf.CheckContext(sconf)[source]#

Bases: object

Provides a context for configure tests. Defines how a test writes to the screen and log file.

A typical test is just a callable with an instance of CheckContext as first argument:

def CheckCustom(context, …):

context.Message(‘Checking my weird test … ‘) ret = myWeirdTestFunction(…) context.Result(ret)

Often, myWeirdTestFunction will be one of context.TryCompile/context.TryLink/context.TryRun. The results of those are cached, for they are only rebuild, if the dependencies have changed.

AppendLIBS(lib_name_list, unique: bool = False)[source]#
BuildProg(text, ext) bool[source]#
CompileProg(text, ext) bool[source]#
CompileSharedObject(text, ext) bool[source]#
Display(msg) None[source]#
Log(msg) None[source]#
Message(text) None[source]#

Inform about what we are doing right now, e.g. ‘Checking for SOMETHING … ‘

PrependLIBS(lib_name_list, unique: bool = False)[source]#
Result(res) None[source]#

Inform about the result of the test. If res is not a string, displays ‘yes’ or ‘no’ depending on whether res is evaluated as true or false. The result is only displayed when self.did_show_result is not set.

RunProg(text, ext)[source]#
SetLIBS(val)[source]#
TryAction(*args, **kw)[source]#
TryBuild(*args, **kw)[source]#
TryCompile(*args, **kw)[source]#
TryRun(*args, **kw)[source]#
SCons.SConf.CheckDeclaration(context, declaration, includes: str = '', language=None) bool[source]#
SCons.SConf.CheckFunc(context, function_name, header=None, language=None) bool[source]#
SCons.SConf.CheckHeader(context, header, include_quotes: str = '<>', language=None) bool[source]#

A test for a C or C++ header file.

SCons.SConf.CheckLib(context, library=None, symbol: str = 'main', header=None, language=None, autoadd: bool = True, append: bool = True, unique: bool = False) bool[source]#

A test for a library. See also CheckLibWithHeader. Note that library may also be None to test whether the given symbol compiles without flags.

SCons.SConf.CheckLibWithHeader(context, libs, header, language, call=None, autoadd: bool = True, append: bool = True, unique: bool = False) bool[source]#

Another (more sophisticated) test for a library. Checks, if library and header is available for language (may be ‘C’ or ‘CXX’). Call maybe be a valid expression _with_ a trailing ‘;’. As in CheckLib, we support library=None, to test if the call compiles without extra link flags.

SCons.SConf.CheckMember(context, aggregate_member, header=None, language=None) bool[source]#

Returns the status (False : failed, True : ok).

SCons.SConf.CheckProg(context, prog_name)[source]#

Simple check if a program exists in the path. Returns the path for the application, or None if not found.

SCons.SConf.CheckSHCC(context) bool[source]#
SCons.SConf.CheckSHCXX(context) bool[source]#
SCons.SConf.CheckType(context, type_name, includes: str = '', language=None) bool[source]#
SCons.SConf.CheckTypeSize(context, type_name, includes: str = '', language=None, expect=None)[source]#
exception SCons.SConf.ConfigureCacheError(target)[source]#

Bases: SConfError

Raised when a use explicitely requested the cache feature, but the test is run the first time.

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.SConf.ConfigureDryRunError(target)[source]#

Bases: SConfError

Raised when a file or directory needs to be updated during a Configure process, but the user requested a dry-run

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

SCons.SConf.CreateConfigHBuilder(env) None[source]#

Called if necessary just before the building targets phase begins.

SCons.SConf.NeedConfigHBuilder() bool[source]#
SCons.SConf.SConf(*args, **kw)[source]#
class SCons.SConf.SConfBase(env, custom_tests={}, conf_dir: str = '$CONFIGUREDIR', log_file: str = '$CONFIGURELOG', config_h=None, _depth: int = 0)[source]#

Bases: object

This is simply a class to represent a configure context. After creating a SConf object, you can call any tests. After finished with your tests, be sure to call the Finish() method, which returns the modified environment. Some words about caching: In most cases, it is not necessary to cache Test results explicitly. Instead, we use the scons dependency checking mechanism. For example, if one wants to compile a test program (SConf.TryLink), the compiler is only called, if the program dependencies have changed. However, if the program could not be compiled in a former SConf run, we need to explicitly cache this error.

AddTest(test_name, test_instance) None[source]#

Adds test_class to this SConf instance. It can be called with self.test_name(…)

AddTests(tests) None[source]#

Adds all the tests given in the tests dictionary to this SConf instance

BuildNodes(nodes)[source]#

Tries to build the given nodes immediately. Returns 1 on success, 0 on error.

Define(name, value=None, comment=None) None[source]#

Define a pre processor symbol name, with the optional given value in the current config header.

If value is None (default), then #define name is written. If value is not none, then #define name value is written.

comment is a string which will be put as a C comment in the header, to explain the meaning of the value (appropriate C comments will be added automatically).

Finish()[source]#

Call this method after finished with your tests: env = sconf.Finish()

class TestWrapper(test, sconf)[source]#

Bases: object

A wrapper around Tests (to ensure sanity)

TryAction(action, text=None, extension: str = '')[source]#

Tries to execute the given action with optional source file contents <text> and optional source file extension <extension>, Returns the status (0 : failed, 1 : ok) and the contents of the output file.

TryBuild(builder, text=None, extension: str = '')[source]#

Low level TryBuild implementation. Normally you don’t need to call that - you can use TryCompile / TryLink / TryRun instead

TryCompile(text, extension)[source]#

Compiles the program given in text to an env.Object, using extension as file extension (e.g. ‘.c’). Returns 1, if compilation was successful, 0 otherwise. The target is saved in self.lastTarget (for further processing).

Compiles the program given in text to an executable env.Program, using extension as file extension (e.g. ‘.c’). Returns 1, if compilation was successful, 0 otherwise. The target is saved in self.lastTarget (for further processing).

TryRun(text, extension)[source]#

Compiles and runs the program given in text, using extension as file extension (e.g. ‘.c’). Returns (1, outputStr) on success, (0, ‘’) otherwise. The target (a file containing the program’s stdout) is saved in self.lastTarget (for further processing).

_createDir(node)[source]#
_shutdown()[source]#

Private method. Reset to non-piped spawn

_startup() None[source]#

Private method. Set up logstream, and set the environment variables necessary for a piped build

pspawn_wrapper(sh, escape, cmd, args, env)[source]#

Wrapper function for handling piped spawns.

This looks to the calling interface (in Action.py) like a “normal” spawn, but associates the call with the PSPAWN variable from the construction environment and with the streams to which we want the output logged. This gets slid into the construction environment as the SPAWN variable so Action.py doesn’t have to know or care whether it’s spawning a piped command or not.

class SCons.SConf.SConfBuildInfo[source]#

Bases: FileBuildInfo

Special build info for targets of configure tests. Additional members are result (did the builder succeed last time?) and string, which contains messages of the original build phase.

__getstate__()#

Return all fields that shall be pickled. Walk the slots in the class hierarchy and add those to the state dictionary. If a ‘__dict__’ slot is available, copy all entries to the dictionary. Also include the version id, which is fixed for all instances of a class.

__setstate__(state) None#

Restore the attributes from a pickled state.

bact#
bactsig#
bdepends#
bdependsigs#
bimplicit#
bimplicitsigs#
bsources#
bsourcesigs#
convert_from_sconsign(dir, name) None#

Converts a newly-read FileBuildInfo object for in-SCons use

For normal up-to-date checking, we don’t have any conversion to perform–but we’re leaving this method here to make that clear.

convert_to_sconsign() None#

Converts this FileBuildInfo object for writing to a .sconsign file

This replaces each Node in our various dependency lists with its usual string representation: relative to the top-level SConstruct directory, or an absolute path if it’s outside.

current_version_id = 2#
dependency_map#
format(names: int = 0)#
merge(other) None#

Merge the fields of another object into this object. Already existing information is overwritten by the other instance’s data. WARNING: If a ‘__dict__’ slot is added, it should be updated instead of replaced.

prepare_dependencies() None#

Prepares a FileBuildInfo object for explaining what changed

The bsources, bdepends and bimplicit lists have all been stored on disk as paths relative to the top-level SConstruct directory. Convert the strings to actual Nodes (for use by the –debug=explain code and –implicit-cache).

result#
set_build_result(result, string) None[source]#
string#
class SCons.SConf.SConfBuildTask(tm, targets, top, node)[source]#

Bases: AlwaysTask

This is almost the same as SCons.Script.BuildTask. Handles SConfErrors correctly and knows about the current cache_mode.

LOGGER = None#
_abc_impl = <_abc._abc_data object>#
_exception_raise()#

Raises a pending exception that was recorded while getting a Task ready for execution.

_no_exception_to_raise() None#
collect_node_states() Tuple[bool, bool, bool][source]#
display(message) None[source]#

Hook to allow the calling interface to display a message.

This hook gets called as part of preparing a task for execution (that is, a Node to be built). As part of figuring out what Node should be built next, the actual target list may be altered, along with a message describing the alteration. The calling interface can subclass Task and provide a concrete implementation of this method to see those messages.

display_cached_string(bi) None[source]#

Logs the original builder messages, given the SConfBuildInfo instance bi.

exc_clear() None#

Clears any recorded exception.

This also changes the “exception_raise” attribute to point to the appropriate do-nothing method.

exc_info()#

Returns info about a recorded exception.

exception_set(exception=None) None#

Records an exception to be raised at the appropriate time.

This also changes the “exception_raise” attribute to point to the method that will, in fact

execute()[source]#

Called to execute the task.

This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in prepare(), executed() or failed().

executed() None#

Called when the task has been successfully executed and the Taskmaster instance wants to call the Node’s callback methods.

This may have been a do-nothing operation (to preserve build order), so we must check the node’s state before deciding whether it was “built”, in which case we call the appropriate Node method. In any event, we always call “visited()”, which will handle any post-visit actions that must take place regardless of whether or not the target was an actual built target or a source Node.

executed_with_callbacks() None#

Called when the task has been successfully executed and the Taskmaster instance wants to call the Node’s callback methods.

This may have been a do-nothing operation (to preserve build order), so we must check the node’s state before deciding whether it was “built”, in which case we call the appropriate Node method. In any event, we always call “visited()”, which will handle any post-visit actions that must take place regardless of whether or not the target was an actual built target or a source Node.

executed_without_callbacks() None#

Called when the task has been successfully executed and the Taskmaster instance doesn’t want to call the Node’s callback methods.

fail_continue() None#

Explicit continue-the-build failure.

This sets failure status on the target nodes and all of their dependent parent nodes.

Note: Although this function is normally invoked on nodes in the executing state, it might also be invoked on up-to-date nodes when using Configure().

fail_stop() None#

Explicit stop-the-build failure.

This sets failure status on the target nodes and all of their dependent parent nodes.

Note: Although this function is normally invoked on nodes in the executing state, it might also be invoked on up-to-date nodes when using Configure().

failed()[source]#

Default action when a task fails: stop the build.

Note: Although this function is normally invoked on nodes in the executing state, it might also be invoked on up-to-date nodes when using Configure().

get_target()#

Fetch the target being built or updated by this task.

make_ready() None#

Marks all targets in a task ready for execution if any target is not current.

This is the default behavior for building only what’s necessary.

make_ready_all() None#

Marks all targets in a task ready for execution.

This is used when the interface needs every target Node to be visited–the canonical example being the “scons -c” option.

make_ready_current() None[source]#

Marks all targets in a task ready for execution if any target is not current.

This is the default behavior for building only what’s necessary.

needs_execute() bool#

Always returns True (indicating this Task should always be executed).

Subclasses that need this behavior (as opposed to the default of only executing Nodes that are out of date w.r.t. their dependencies) can use this as follows:

class MyTaskSubclass(SCons.Taskmaster.Task):

needs_execute = SCons.Taskmaster.AlwaysTask.needs_execute

non_sconf_nodes = {}#
postprocess() None[source]#

Post-processes a task after it’s been executed.

This examines all the targets just built (or not, we don’t care if the build was successful, or even if there was no build because everything was up-to-date) to see if they have any waiting parent Nodes, or Nodes waiting on a common side effect, that can be put back on the candidates list.

prepare() None#

Called just before the task is executed.

This is mainly intended to give the target Nodes a chance to unlink underlying files and make all necessary directories before the Action is actually called to build the targets.

trace_message(node, description: str = 'node') None#
exception SCons.SConf.SConfError(msg)[source]#

Bases: UserError

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.SConf.SConfWarning[source]#

Bases: SConsWarning

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

SCons.SConf.SetBuildType(buildtype) None[source]#
SCons.SConf.SetCacheMode(mode)[source]#

Set the Configure cache mode. mode must be one of “auto”, “force”, or “cache”.

SCons.SConf.SetProgressDisplay(display) None[source]#

Set the progress display to use (called from SCons.Script)

class SCons.SConf.Streamer(orig)[source]#

Bases: object

‘Sniffer’ for a file-like writable object. Similar to the unix tool tee.

flush() None[source]#
getvalue()[source]#

Return everything written to orig since the Streamer was created.

write(str) None[source]#
writelines(lines) None[source]#
SCons.SConf._createConfigH(target, source, env) None[source]#
SCons.SConf._createSource(target, source, env) None[source]#
SCons.SConf._set_conftest_node(node) None[source]#
SCons.SConf._stringConfigH(target, source, env)[source]#
SCons.SConf._stringSource(target, source, env)[source]#
SCons.SConf.createIncludesFromHeaders(headers, leaveLast, include_quotes: str = '""')[source]#

SCons.SConsign module#

Operations on signature database files (.sconsign).

class SCons.SConsign.Base[source]#

Bases: object

This is the controlling class for the signatures for the collection of entries associated with a specific directory. The actual directory association will be maintained by a subclass that is specific to the underlying storage method. This class provides a common set of methods for fetching and storing the individual bits of information that make up signature entry.

do_not_set_entry(filename, obj) None[source]#
do_not_store_info(filename, node) None[source]#
get_entry(filename)[source]#

Fetch the specified entry attribute.

merge() None[source]#
set_entry(filename, obj) None[source]#

Set the entry.

store_info(filename, node) None[source]#
class SCons.SConsign.DB(dir)[source]#

Bases: Base

A Base subclass that reads and writes signature information from a global .sconsign.db* file–the actual file suffix is determined by the database module.

do_not_set_entry(filename, obj) None#
do_not_store_info(filename, node) None#
get_entry(filename)#

Fetch the specified entry attribute.

merge() None#
set_entry(filename, obj) None#

Set the entry.

store_info(filename, node) None#
write(sync: int = 1) None[source]#
class SCons.SConsign.Dir(fp=None, dir=None)[source]#

Bases: Base

do_not_set_entry(filename, obj) None#
do_not_store_info(filename, node) None#
get_entry(filename)#

Fetch the specified entry attribute.

merge() None#
set_entry(filename, obj) None#

Set the entry.

store_info(filename, node) None#
class SCons.SConsign.DirFile(dir)[source]#

Bases: Dir

Encapsulates reading and writing a per-directory .sconsign file.

do_not_set_entry(filename, obj) None#
do_not_store_info(filename, node) None#
get_entry(filename)#

Fetch the specified entry attribute.

merge() None#
set_entry(filename, obj) None#

Set the entry.

store_info(filename, node) None#
write(sync: int = 1) None[source]#

Write the .sconsign file to disk.

Try to write to a temporary file first, and rename it if we succeed. If we can’t write to the temporary file, it’s probably because the directory isn’t writable (and if so, how did we build anything in this directory, anyway?), so try to write directly to the .sconsign file as a backup. If we can’t rename, try to copy the temporary contents back to the .sconsign file. Either way, always try to remove the temporary file at the end.

SCons.SConsign.File(name, dbm_module=None) None[source]#

Arrange for all signatures to be stored in a global .sconsign.db* file.

SCons.SConsign.ForDirectory#

alias of DB

SCons.SConsign.Get_DataBase(dir)[source]#
SCons.SConsign.Reset() None[source]#

Reset global state. Used by unit tests that end up using SConsign multiple times to get a clean slate for each test.

class SCons.SConsign.SConsignEntry[source]#

Bases: object

Wrapper class for the generic entry in a .sconsign file. The Node subclass populates it with attributes as it pleases.

XXX As coded below, we do expect a ‘.binfo’ attribute to be added, but we’ll probably generalize this in the next refactorings.

binfo#
convert_from_sconsign(dir, name) None[source]#
convert_to_sconsign() None[source]#
current_version_id = 2#
ninfo#
SCons.SConsign.corrupt_dblite_warning(filename) None[source]#
SCons.SConsign.current_sconsign_filename()[source]#
SCons.SConsign.write() None[source]#

SCons.Subst module#

SCons string substitution.

class SCons.Subst.CmdStringHolder(cmd, literal=None)[source]#

Bases: UserString

This is a special class used to hold strings generated by scons_subst() and scons_subst_list(). It defines a special method escape(). When passed a function with an escape algorithm for a particular platform, it will return the contained string with the proper escape sequences inserted.

_abc_impl = <_abc._abc_data object>#
capitalize()#
casefold()#
center(width, *args)#
count(value) integer -- return number of occurrences of value#
encode(encoding='utf-8', errors='strict')#
endswith(suffix, start=0, end=9223372036854775807)#
escape(escape_func, quote_func=<function quote_spaces>)[source]#

Escape the string with the supplied function. The function is expected to take an arbitrary string, then return it with all special characters escaped and ready for passing to the command interpreter.

After calling this function, the next call to str() will return the escaped string.

expandtabs(tabsize=8)#
find(sub, start=0, end=9223372036854775807)#
format(*args, **kwds)#
format_map(mapping)#
index(value[, start[, stop]]) integer -- return first index of value.#

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

is_literal() bool[source]#
isalnum()#
isalpha()#
isascii()#
isdecimal()#
isdigit()#
isidentifier()#
islower()#
isnumeric()#
isprintable()#
isspace()#
istitle()#
isupper()#
join(seq)#
ljust(width, *args)#
lower()#
lstrip(chars=None)#
maketrans()#

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

partition(sep)#
removeprefix(prefix, /)#
removesuffix(suffix, /)#
replace(old, new, maxsplit=-1)#
rfind(sub, start=0, end=9223372036854775807)#
rindex(sub, start=0, end=9223372036854775807)#
rjust(width, *args)#
rpartition(sep)#
rsplit(sep=None, maxsplit=-1)#
rstrip(chars=None)#
split(sep=None, maxsplit=-1)#
splitlines(keepends=False)#
startswith(prefix, start=0, end=9223372036854775807)#
strip(chars=None)#
swapcase()#
title()#
translate(*args)#
upper()#
zfill(width)#
class SCons.Subst.ListSubber(env, mode, conv, gvars)[source]#

Bases: UserList

A class to construct the results of a scons_subst_list() call.

Like StringSubber, this class binds a specific construction environment, mode, target and source with two methods (substitute() and expand()) that handle the expansion.

In addition, however, this class is used to track the state of the result(s) we’re gathering so we can do the appropriate thing whenever we have to append another word to the result–start a new line, start a new word, append to the current word, etc. We do this by setting the “append” attribute to the right method so that our wrapper methods only need ever call ListSubber.append(), and the rest of the object takes care of doing the right thing internally.

_abc_impl = <_abc._abc_data object>#
add_new_word(x) None[source]#
add_to_current_word(x) None[source]#

Append the string x to the end of the current last word in the result. If that is not possible, then just add it as a new word. Make sure the entire concatenated string inherits the object attributes of x (in particular, the escape function) by wrapping it as CmdStringHolder.

append(item)#

S.append(value) – append value to the end of the sequence

clear() None -- remove all items from S#
close_strip(x) None[source]#

Handle the “close strip” $) token.

copy()#
count(value) integer -- return number of occurrences of value#
expand(s, lvars, within_list)[source]#

Expand a single “token” as necessary, appending the expansion to the current result.

This handles expanding different types of things (strings, lists, callables) appropriately. It calls the wrapper substitute() method to re-expand things as necessary, so that the results of expansions of side-by-side strings still get re-evaluated separately, not smushed together.

expanded(s) bool[source]#

Determines if the string s requires further expansion.

Due to the implementation of ListSubber expand will call itself 2 additional times for an already expanded string. This method is used to determine if a string is already fully expanded and if so exit the loop early to prevent these recursive calls.

extend(other)#

S.extend(iterable) – extend sequence by appending elements from the iterable

index(value[, start[, stop]]) integer -- return first index of value.#

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

insert(i, item)#

S.insert(index, value) – insert value before index

literal(x)[source]#
next_line() None[source]#

Arrange for the next word to start a new line. This is like starting a new word, except that we have to append another line to the result.

next_word() None[source]#

Arrange for the next word to start a new word.

open_strip(x) None[source]#

Handle the “open strip” $( token.

pop([index]) item -- remove and return item at index (default last).#

Raise IndexError if list is empty or index is out of range.

remove(item)#

S.remove(value) – remove first occurrence of value. Raise ValueError if the value is not present.

reverse()#

S.reverse() – reverse IN PLACE

sort(*args, **kwds)#
substitute(args, lvars, within_list) None[source]#

Substitute expansions in an argument or list of arguments.

This serves as a wrapper for splitting up a string into separate tokens.

this_word() None[source]#

Arrange for the next word to append to the end of the current last word in the result.

class SCons.Subst.Literal(lstr)[source]#

Bases: object

A wrapper for a string. If you use this object wrapped around a string, then it will be interpreted as literal. When passed to the command interpreter, all special characters will be escaped.

escape(escape_func)[source]#
for_signature()[source]#
is_literal() bool[source]#
class SCons.Subst.NLWrapper(list, func)[source]#

Bases: object

A wrapper class that delays turning a list of sources or targets into a NodeList until it’s needed. The specified function supplied when the object is initialized is responsible for turning raw nodes into proxies that implement the special attributes like .abspath, .source, etc. This way, we avoid creating those proxies just “in case” someone is going to use $TARGET or the like, and only go through the trouble if we really have to.

In practice, this might be a wash performance-wise, but it’s a little cleaner conceptually…

_create_nodelist()#
_gen_nodelist()[source]#
_return_nodelist()[source]#
class SCons.Subst.NullNodeList(*args, **kwargs)[source]#

Bases: NullSeq

_instance#
SCons.Subst.SetAllowableExceptions(*excepts) None[source]#
class SCons.Subst.SpecialAttrWrapper(lstr, for_signature=None)[source]#

Bases: object

This is a wrapper for what we call a ‘Node special attribute.’ This is any of the attributes of a Node that we can reference from Environment variable substitution, such as $TARGET.abspath or $SOURCES[1].filebase. We implement the same methods as Literal so we can handle special characters, plus a for_signature method, such that we can return some canonical string during signature calculation to avoid unnecessary rebuilds.

escape(escape_func)[source]#
for_signature()[source]#
is_literal() bool[source]#
class SCons.Subst.StringSubber(env, mode, conv, gvars)[source]#

Bases: object

A class to construct the results of a scons_subst() call.

This binds a specific construction environment, mode, target and source with two methods (substitute() and expand()) that handle the expansion.

expand(s, lvars)[source]#

Expand a single “token” as necessary, returning an appropriate string containing the expansion.

This handles expanding different types of things (strings, lists, callables) appropriately. It calls the wrapper substitute() method to re-expand things as necessary, so that the results of expansions of side-by-side strings still get re-evaluated separately, not smushed together.

substitute(args, lvars)[source]#

Substitute expansions in an argument or list of arguments.

This serves as a wrapper for splitting up a string into separate tokens.

class SCons.Subst.Target_or_Source(nl)[source]#

Bases: object

A class that implements $TARGET or $SOURCE expansions by in turn wrapping a NLWrapper. This class handles the different methods used to access an individual proxy Node, calling the NLWrapper to create a proxy on demand.

class SCons.Subst.Targets_or_Sources(nl)[source]#

Bases: UserList

A class that implements $TARGETS or $SOURCES expansions by in turn wrapping a NLWrapper. This class handles the different methods used to access the list, calling the NLWrapper to create proxies on demand.

Note that we subclass collections.UserList purely so that the is_Sequence() function will identify an object of this class as a list during variable expansion. We’re not really using any collections.UserList methods in practice.

_abc_impl = <_abc._abc_data object>#
append(item)#

S.append(value) – append value to the end of the sequence

clear() None -- remove all items from S#
copy()#
count(value) integer -- return number of occurrences of value#
extend(other)#

S.extend(iterable) – extend sequence by appending elements from the iterable

index(value[, start[, stop]]) integer -- return first index of value.#

Raises ValueError if the value is not present.

Supporting start and stop arguments is optional, but recommended.

insert(i, item)#

S.insert(index, value) – insert value before index

pop([index]) item -- remove and return item at index (default last).#

Raise IndexError if list is empty or index is out of range.

remove(item)#

S.remove(value) – remove first occurrence of value. Raise ValueError if the value is not present.

reverse()#

S.reverse() – reverse IN PLACE

sort(*args, **kwds)#
SCons.Subst._remove_list(list)[source]#
SCons.Subst._rm_list(list)[source]#
SCons.Subst.escape_list(mylist, escape_func)[source]#

Escape a list of arguments by running the specified escape_func on every object in the list that has an escape() method.

SCons.Subst.quote_spaces(arg)[source]#

Generic function for putting double quotes around any string that has white space in it.

SCons.Subst.raise_exception(exception, target, s)[source]#
SCons.Subst.scons_subst(strSubst, env, mode=1, target=None, source=None, gvars={}, lvars={}, conv=None, overrides: dict | None = None)[source]#

Expand a string or list containing construction variable substitutions.

This is the work-horse function for substitutions in file names and the like. The companion scons_subst_list() function (below) handles separating command lines into lists of arguments, so see that function if that’s what you’re looking for.

SCons.Subst.scons_subst_list(strSubst, env, mode=1, target=None, source=None, gvars={}, lvars={}, conv=None, overrides: dict | None = None)[source]#

Substitute construction variables in a string (or list or other object) and separate the arguments into a command list.

The companion scons_subst() function (above) handles basic substitutions within strings, so see that function instead if that’s what you’re looking for.

SCons.Subst.scons_subst_once(strSubst, env, key)[source]#

Perform single (non-recursive) substitution of a single construction variable keyword.

This is used when setting a variable when copying or overriding values in an Environment. We want to capture (expand) the old value before we override it, so people can do things like:

env2 = env.Clone(CCFLAGS = ‘$CCFLAGS -g’)

We do this with some straightforward, brute-force code here…

SCons.Subst.subst_dict(target, source)[source]#

Create a dictionary for substitution of special construction variables.

This translates the following special arguments:

target - the target (object or array of objects),

used to generate the TARGET and TARGETS construction variables

source - the source (object or array of objects),

used to generate the SOURCES and SOURCE construction variables

SCons.Warnings module#

The SCons warnings framework.

exception SCons.Warnings.CacheCleanupErrorWarning[source]#

Bases: SConsWarning

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.CacheVersionWarning[source]#

Bases: WarningOnByDefault

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.CacheWriteErrorWarning[source]#

Bases: SConsWarning

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.CorruptSConsignWarning[source]#

Bases: WarningOnByDefault

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.DependencyWarning[source]#

Bases: SConsWarning

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.DeprecatedDebugOptionsWarning[source]#

Bases: MandatoryDeprecatedWarning

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.DeprecatedMissingSConscriptWarning[source]#

Bases: DeprecatedWarning

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.DeprecatedOptionsWarning[source]#

Bases: MandatoryDeprecatedWarning

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.DeprecatedSourceCodeWarning[source]#

Bases: FutureDeprecatedWarning

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.DeprecatedWarning[source]#

Bases: SConsWarning

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.DevelopmentVersionWarning[source]#

Bases: WarningOnByDefault

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.DuplicateEnvironmentWarning[source]#

Bases: WarningOnByDefault

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.FortranCxxMixWarning[source]#

Bases: LinkWarning

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.FutureDeprecatedWarning[source]#

Bases: SConsWarning

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.FutureReservedVariableWarning[source]#

Bases: WarningOnByDefault

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.LinkWarning[source]#

Bases: WarningOnByDefault

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.MandatoryDeprecatedWarning[source]#

Bases: DeprecatedWarning

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.MisleadingKeywordsWarning[source]#

Bases: WarningOnByDefault

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.MissingSConscriptWarning[source]#

Bases: WarningOnByDefault

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.NoObjectCountWarning[source]#

Bases: WarningOnByDefault

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.NoParallelSupportWarning[source]#

Bases: WarningOnByDefault

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.PythonVersionWarning[source]#

Bases: DeprecatedWarning

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.ReservedVariableWarning[source]#

Bases: WarningOnByDefault

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.SConsWarning[source]#

Bases: UserError

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.StackSizeWarning[source]#

Bases: WarningOnByDefault

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.TargetNotBuiltWarning[source]#

Bases: SConsWarning

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.TaskmasterNeedsExecuteWarning[source]#

Bases: DeprecatedWarning

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.ToolQtDeprecatedWarning[source]#

Bases: DeprecatedWarning

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.VisualCMissingWarning[source]#

Bases: WarningOnByDefault

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.VisualStudioMissingWarning[source]#

Bases: SConsWarning

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.VisualVersionMismatch[source]#

Bases: WarningOnByDefault

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception SCons.Warnings.WarningOnByDefault[source]#

Bases: SConsWarning

add_note()#

Exception.add_note(note) – add a note to the exception

args#
with_traceback()#

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

SCons.Warnings.enableWarningClass(clazz) None[source]#

Enables all warnings of type clazz or derived from clazz.

SCons.Warnings.process_warn_strings(arguments) None[source]#

Process requests to enable/disable warnings.

The requests are strings passed to the –warn option or the SetOption(‘warn’) function.

An argument to this option should be of the form “warning-class” or “no-warning-class”. The warning class is munged and has the suffix “Warning” added in order to get an actual class name from the classes above, which we need to pass to the {enable,disable}WarningClass() functions.

For example, “deprecated” will enable the DeprecatedWarning class. “no-dependency” will disable the DependencyWarning class.

As a special case, –warn=all and –warn=no-all will enable or disable (respectively) the base class of all SCons warnings.

SCons.Warnings.suppressWarningClass(clazz) None[source]#

Suppresses all warnings of type clazz or derived from clazz.

SCons.Warnings.warn(clazz, *args)[source]#

Issue a warning, accounting for SCons rules.

Check if warnings for this class are enabled. If warnings are treated as exceptions, raise exception. Use the global warning-emitter _warningOut, which allows selecting different ways of presenting a traceback (see Script/Main.py)

SCons.Warnings.warningAsException(flag: bool = True)[source]#

Set global _warningAsExeption flag.

Parameters:

flag – value to set warnings-as-exceptions to [default: True]

Returns:

The previous value.

SCons.cpp module#

SCons C Pre-Processor module

SCons.cpp.CPP_to_Python(s)[source]#

Converts a C pre-processor expression into an equivalent Python expression that can be evaluated.

SCons.cpp.CPP_to_Python_Ops_Sub(m)#
SCons.cpp.Cleanup_CPP_Expressions(ts)[source]#
class SCons.cpp.DumbPreProcessor(*args, **kw)[source]#

Bases: PreProcessor

A preprocessor that ignores all #if/#elif/#else/#endif directives and just reports back all of the #include files (like the classic SCons scanner did).

This is functionally equivalent to using a regular expression to find all of the #include lines, only slower. It exists mainly as an example of how the main PreProcessor class can be sub-classed to tailor its behavior.

__call__(file)#

Pre-processes a file.

This is the main public entry point.

_do_if_else_condition(condition) None#

Common logic for evaluating the conditions on #if, #ifdef and #ifndef lines.

_match_tuples(tuples)#
_parse_tuples(contents)#
_process_tuples(tuples, file=None)#
all_include(t) None#
do_define(t) None#

Default handling of a #define line.

do_elif(t) None#

Default handling of a #elif line.

do_else(t) None#

Default handling of a #else line.

do_endif(t) None#

Default handling of a #endif line.

do_if(t) None#

Default handling of a #if line.

do_ifdef(t) None#

Default handling of a #ifdef line.

do_ifndef(t) None#

Default handling of a #ifndef line.

do_import(t) None#

Default handling of a #import line.

do_include(t) None#

Default handling of a #include line.

do_include_next(t) None#

Default handling of a #include line.

do_nothing(t) None#

Null method for when we explicitly want the action for a specific preprocessor directive to do nothing.

do_undef(t) None#

Default handling of a #undef line.

eval_expression(t)#

Evaluates a C preprocessor expression.

This is done by converting it to a Python equivalent and eval()ing it in the C preprocessor namespace we use to track #define values.

finalize_result(fname)#
find_include_file(t)#

Finds the #include file for a given preprocessor tuple.

initialize_result(fname) None#
process_contents(contents)#

Pre-processes a file contents.

Is used by tests

process_file(file)#

Pre-processes a file.

This is the main internal entry point.

read_file(file)#
resolve_include(t)#

Resolve a tuple-ized #include line.

This handles recursive expansion of values without “” or <> surrounding the name until an initial “ or < is found, to handle #include FILE where FILE is a #define somewhere else.

restore() None#

Pops the previous dispatch table off the stack and makes it the current one.

save() None#

Pushes the current dispatch table on the stack and re-initializes the current dispatch table to the default.

scons_current_file(t) None#
start_handling_includes(t=None) None#

Causes the PreProcessor object to start processing #import, #include and #include_next lines.

This method will be called when a #if, #ifdef, #ifndef or #elif evaluates True, or when we reach the #else in a #if, #ifdef, #ifndef or #elif block where a condition already evaluated False.

stop_handling_includes(t=None) None#

Causes the PreProcessor object to stop processing #import, #include and #include_next lines.

This method will be called when a #if, #ifdef, #ifndef or #elif evaluates False, or when we reach the #else in a #if, #ifdef, #ifndef or #elif block where a condition already evaluated True.

tupleize(contents)#

Turns the contents of a file into a list of easily-processed tuples describing the CPP lines in the file.

The first element of each tuple is the line’s preprocessor directive (#if, #include, #define, etc., minus the initial ‘#’). The remaining elements are specific to the type of directive, as pulled apart by the regular expression.

class SCons.cpp.FunctionEvaluator(name, args, expansion)[source]#

Bases: object

Handles delayed evaluation of a #define function call.

__call__(*values)[source]#

Evaluates the expansion of a #define macro function called with the specified values.

class SCons.cpp.PreProcessor(current='.', cpppath=(), dict={}, all: int = 0, depth=-1)[source]#

Bases: object

The main workhorse class for handling C pre-processing.

__call__(file)[source]#

Pre-processes a file.

This is the main public entry point.

_do_if_else_condition(condition) None[source]#

Common logic for evaluating the conditions on #if, #ifdef and #ifndef lines.

_match_tuples(tuples)[source]#
_parse_tuples(contents)[source]#
_process_tuples(tuples, file=None)[source]#
all_include(t) None[source]#
do_define(t) None[source]#

Default handling of a #define line.

do_elif(t) None[source]#

Default handling of a #elif line.

do_else(t) None[source]#

Default handling of a #else line.

do_endif(t) None[source]#

Default handling of a #endif line.

do_if(t) None[source]#

Default handling of a #if line.

do_ifdef(t) None[source]#

Default handling of a #ifdef line.

do_ifndef(t) None[source]#

Default handling of a #ifndef line.

do_import(t) None[source]#

Default handling of a #import line.

do_include(t) None[source]#

Default handling of a #include line.

do_include_next(t) None#

Default handling of a #include line.

do_nothing(t) None[source]#

Null method for when we explicitly want the action for a specific preprocessor directive to do nothing.

do_undef(t) None[source]#

Default handling of a #undef line.

eval_expression(t)[source]#

Evaluates a C preprocessor expression.

This is done by converting it to a Python equivalent and eval()ing it in the C preprocessor namespace we use to track #define values.

finalize_result(fname)[source]#
find_include_file(t)[source]#

Finds the #include file for a given preprocessor tuple.

initialize_result(fname) None[source]#
process_contents(contents)[source]#

Pre-processes a file contents.

Is used by tests

process_file(file)[source]#

Pre-processes a file.

This is the main internal entry point.

read_file(file)[source]#
resolve_include(t)[source]#

Resolve a tuple-ized #include line.

This handles recursive expansion of values without “” or <> surrounding the name until an initial “ or < is found, to handle #include FILE where FILE is a #define somewhere else.

restore() None[source]#

Pops the previous dispatch table off the stack and makes it the current one.

save() None[source]#

Pushes the current dispatch table on the stack and re-initializes the current dispatch table to the default.

scons_current_file(t) None[source]#
start_handling_includes(t=None) None[source]#

Causes the PreProcessor object to start processing #import, #include and #include_next lines.

This method will be called when a #if, #ifdef, #ifndef or #elif evaluates True, or when we reach the #else in a #if, #ifdef, #ifndef or #elif block where a condition already evaluated False.

stop_handling_includes(t=None) None[source]#

Causes the PreProcessor object to stop processing #import, #include and #include_next lines.

This method will be called when a #if, #ifdef, #ifndef or #elif evaluates False, or when we reach the #else in a #if, #ifdef, #ifndef or #elif block where a condition already evaluated True.

tupleize(contents)[source]#

Turns the contents of a file into a list of easily-processed tuples describing the CPP lines in the file.

The first element of each tuple is the line’s preprocessor directive (#if, #include, #define, etc., minus the initial ‘#’). The remaining elements are specific to the type of directive, as pulled apart by the regular expression.

SCons.dblite module#

dblite.py module contributed by Ralf W. Grosse-Kunstleve. Extended for Unicode by Steven Knight.

This is a very simple-minded “database” used for saved signature information, with an interface modeled on the Python dbm database interface module.

class SCons.dblite._Dblite(file_base_name, flag='r', mode=438)[source]#

Bases: object

Lightweight signature database class.

Behaves like a dict when in memory, loads from a pickled disk file on open and writes back out to it on close.

Open the database file using a path derived from file_base_name. The optional flag argument can be:

Value

Meaning

'r'

Open existing database for reading only (default)

'w'

Open existing database for reading and writing

'c'

Open database for reading and writing, creating it if it doesn’t exist

'n'

Always create a new, empty database, open for reading and writing

The optional mode argument is the POSIX mode of the file, used only when the database has to be created. It defaults to octal 0o666.

_check_writable()[source]#
static _open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)#

Open file and return a stream. Raise OSError upon failure.

file is either a text or byte string giving the name (and the path if the file isn’t in the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)

mode is an optional string that specifies the mode in which the file is opened. It defaults to ‘r’ which means open for reading in text mode. Other common values are ‘w’ for writing (truncating the file if it already exists), ‘x’ for creating and writing to a new file, and ‘a’ for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent: locale.getencoding() is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are:

Character

Meaning

‘r’

open for reading (default)

‘w’

open for writing, truncating the file first

‘x’

create a new file and open it for writing

‘a’

open for writing, appending to the end of the file if it exists

‘b’

binary mode

‘t’

text mode (default)

‘+’

open a disk file for updating (reading and writing)

The default mode is ‘rt’ (open for reading text). For binary random access, the mode ‘w+b’ opens and truncates the file to 0 bytes, while ‘r+b’ opens the file without truncation. The ‘x’ mode implies ‘w’ and raises an FileExistsError if the file already exists.

Python distinguishes between files opened in binary and text modes, even when the underlying operating system doesn’t. Files opened in binary mode (appending ‘b’ to the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when ‘t’ is appended to the mode argument), the contents of the file are returned as strings, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.

buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows:

  • Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device’s “block size” and falling back on io.DEFAULT_BUFFER_SIZE. On many systems, the buffer will typically be 4096 or 8192 bytes long.

  • “Interactive” text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files.

encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent, but any encoding supported by Python can be passed. See the codecs module for the list of supported encodings.

errors is an optional string that specifies how encoding errors are to be handled—this argument should not be used in binary mode. Pass ‘strict’ to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass ‘ignore’ to ignore errors. (Note that ignoring encoding errors can lead to data loss.) See the documentation for codecs.register or run ‘help(codecs.Codec)’ for a list of the permitted encoding error strings.

newline controls how universal newlines works (it only applies to text mode). It can be None, ‘’, ‘n’, ‘r’, and ‘rn’. It works as follows:

  • On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in ‘n’, ‘r’, or ‘rn’, and these are translated into ‘n’ before being returned to the caller. If it is ‘’, universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.

  • On output, if newline is None, any ‘n’ characters written are translated to the system default line separator, os.linesep. If newline is ‘’ or ‘n’, no translation takes place. If newline is any of the other legal values, any ‘n’ characters written are translated to the given string.

If closefd is False, the underlying file descriptor will be kept open when the file is closed. This does not work when a file name is given and must be True in that case.

A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with (file, flags). opener must return an open file descriptor (passing os.open as opener results in functionality similar to passing None).

open() returns a file object whose type depends on the mode, and through which the standard file operations such as reading and writing are performed. When open() is used to open a file in a text mode (‘w’, ‘r’, ‘wt’, ‘rt’, etc.), it returns a TextIOWrapper. When used to open a file in a binary mode, the returned class varies: in read binary mode, it returns a BufferedReader; in write binary and append binary modes, it returns a BufferedWriter, and in read/write mode, it returns a BufferedRandom.

It is also possible to use a string or bytearray as a file for both reading and writing. For strings StringIO can be used like a file opened in a text mode, and for bytes a BytesIO can be used like a file opened in a binary mode.

static _os_chmod(path, mode, *, dir_fd=None, follow_symlinks=True)#

Change the access permissions of a file.

path

Path to be modified. May always be specified as a str, bytes, or a path-like object. On some platforms, path may also be specified as an open file descriptor. If this functionality is unavailable, using it raises an exception.

mode

Operating-system mode bitfield.

dir_fd

If not None, it should be a file descriptor open to a directory, and path should be relative; path will then be relative to that directory.

follow_symlinks

If False, and the last element of the path is a symbolic link, chmod will modify the symbolic link itself instead of the file the link points to.

It is an error to use dir_fd or follow_symlinks when specifying path as

an open file descriptor.

dir_fd and follow_symlinks may not be implemented on your platform.

If they are unavailable, using them will raise a NotImplementedError.

static _os_chown(path, uid, gid, *, dir_fd=None, follow_symlinks=True)#

Change the owner and group id of path to the numeric uid and gid.

path

Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.

dir_fd

If not None, it should be a file descriptor open to a directory, and path should be relative; path will then be relative to that directory.

follow_symlinks

If False, and the last element of the path is a symbolic link, stat will examine the symbolic link itself instead of the file the link points to.

path may always be specified as a string. On some platforms, path may also be specified as an open file descriptor.

If this functionality is unavailable, using it raises an exception.

If dir_fd is not None, it should be a file descriptor open to a directory,

and path should be relative; path will then be relative to that directory.

If follow_symlinks is False, and the last element of the path is a symbolic

link, chown will modify the symbolic link itself instead of the file the link points to.

It is an error to use dir_fd or follow_symlinks when specifying path as

an open file descriptor.

dir_fd and follow_symlinks may not be implemented on your platform.

If they are unavailable, using them will raise a NotImplementedError.

static _os_replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)#

Rename a file or directory, overwriting the destination.

If either src_dir_fd or dst_dir_fd is not None, it should be a file

descriptor open to a directory, and the respective path string (src or dst) should be relative; the path will then be relative to that directory.

src_dir_fd and dst_dir_fd, may not be implemented on your platform.

If they are unavailable, using them will raise a NotImplementedError.

static _pickle_dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None)#

Write a pickled representation of obj to the open file object file.

This is equivalent to Pickler(file, protocol).dump(obj), but may be more efficient.

The optional protocol argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2, 3, 4 and 5. The default protocol is 4. It was introduced in Python 3.4, and is incompatible with previous versions.

Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced.

The file argument must have a write() method that accepts a single bytes argument. It can thus be a file object opened for binary writing, an io.BytesIO instance, or any other custom object that meets this interface.

If fix_imports is True and protocol is less than 3, pickle will try to map the new Python 3 names to the old module names used in Python 2, so that the pickle data stream is readable with Python 2.

If buffer_callback is None (the default), buffer views are serialized into file as part of the pickle stream. It is an error if buffer_callback is not None and protocol is None or smaller than 5.

_pickle_protocol = 4#
static _shutil_copyfile(src, dst, *, follow_symlinks=True)#

Copy data from src to dst in the most efficient way possible.

If follow_symlinks is not set and src is a symbolic link, a new symlink will be created instead of copying the file it points to.

static _time_time()#

time() -> floating point number

Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them.

close() None[source]#
items()[source]#
keys()[source]#
opener(path, flags)[source]#

Database open helper when creation may be needed.

The high-level Python open() function cannot specify a file mode for creation. Using this as the opener with the saved mode lets us do that.

sync() None[source]#

Flush the database to disk.

This routine must succeed, since the in-memory and on-disk copies are out of sync as soon as we do anything that changes the in-memory version. Thus, to be cautious, flush to a temporary file and then move it over with some error handling.

values()[source]#
SCons.dblite._exercise()[source]#
SCons.dblite.open(file, flag='r', mode: int = 438)[source]#

SCons.exitfuncs module#

Register functions which are executed when SCons exits for any reason.

SCons.exitfuncs._run_exitfuncs() None[source]#

run any registered exit functions

_exithandlers is traversed in reverse order so functions are executed last in, first out.

SCons.exitfuncs.register(func, *targs, **kargs) None[source]#

register a function to be executed upon normal program termination

func - function to be called at exit targs - optional arguments to pass to func kargs - optional keyword arguments to pass to func