SCons package
Contents
SCons package#
Module contents#
Subpackages#
- SCons.Node package
- SCons.Platform package
- Submodules
- SCons.Platform.aix module
- SCons.Platform.cygwin module
- SCons.Platform.darwin module
- SCons.Platform.hpux module
- SCons.Platform.irix module
- SCons.Platform.mingw module
- SCons.Platform.os2 module
- SCons.Platform.posix module
- SCons.Platform.sunos module
- SCons.Platform.virtualenv module
- SCons.Platform.win32 module
- Module contents
- SCons.Scanner package
- SCons.Script package
- SCons.Taskmaster package
- SCons.Tool package
- SCons.Variables package
- SCons.compat package
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.
- class SCons.Action.ActionBase[source]#
Bases:
object
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.
- batch_key(env, target, 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.
- 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:
SCons.Action._ActionAction
Class for command-execution actions.
- _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)#
- 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)#
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.
- class SCons.Action.CommandGeneratorAction(generator, kw)[source]#
Bases:
SCons.Action.ActionBase
Class for command-generator actions.
- get_contents(target, source, env)#
- 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.
- no_batch_key(env, target, source)#
- presub_lines(env)#
- class SCons.Action.FunctionAction(execfunction, kw)[source]#
Bases:
SCons.Action._ActionAction
Class for Python function actions.
- batch_key(env, target, source)#
- genstring(target, source, env)#
- get_contents(target, source, env)#
- 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)#
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.
- class SCons.Action.LazyAction(var, kw)[source]#
Bases:
SCons.Action.CommandGeneratorAction
,SCons.Action.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.
- _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)#
- get_contents(target, source, env)#
- get_implicit_deps(target, source, env, executor=None)#
Return the implicit dependencies of this action’s command line.
- get_presig(target, source, env)[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.
- no_batch_key(env, target, source)#
- presub_lines(env)#
- print_cmd_line(s, target, source, env)#
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=False)#
- strfunction(target, source, env, executor=None, overrides=False)#
- class SCons.Action.ListAction(actionlist)[source]#
Bases:
SCons.Action.ActionBase
Class for lists of other actions.
- batch_key(env, target, source)#
- get_contents(target, source, env)#
- get_presig(target, source, env)[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.
- no_batch_key(env, target, 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='$TARGETS', **kw)[source]#
Bases:
SCons.Action.ActionBase
Base class for actions that create output objects.
- batch_key(env, target, source)#
- genstring(target, source, env)#
- get_contents(target, source, env)#
- 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)#
- SCons.Action._callable_contents(obj)[source]#
Return the signature contents of a callable Python object.
- SCons.Action._code_contents(code, docstring=None)[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]#
This is the actual “implementation” for the Action factory method, below. 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)[source]#
A factory for list actions. Convert the input list into Actions and then wrap them in a ListAction.
- SCons.Action._function_contents(func)[source]#
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.
- Returns
Signature contents of a function. (in bytes)
- SCons.Action._object_contents(obj)[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 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.
- 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 namedSCons
, it blocks access to the global variable, so we move it here to prevent complaints about local variables being used uninitialized.
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.
- class SCons.Builder.BuilderBase(action=None, prefix='', suffix='', src_suffix='', target_factory=None, source_factory=None, target_scanner=None, source_scanner=None, emitter=None, multi=0, env=None, single_source=0, name=None, chdir=<class 'SCons.Builder._Null'>, is_explicit=1, src_builder=None, ensure_suffix=False, **overrides)[source]#
Bases:
object
Base class for Builders, objects that create output nodes (files) from input nodes (files).
- _create_nodes(env, target=None, source=None)[source]#
Create and return lists of target and source nodes.
- _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.
- add_emitter(suffix, emitter)[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)[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.
- 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_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.
- class SCons.Builder.CallableSelector[source]#
Bases:
SCons.Util.Selector
A callable dictionary that will, in turn, call the value it finds if it can.
- clear() None. Remove all items from od. #
- copy() a shallow copy of od #
- fromkeys(value=None)#
Create a new ordered 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 #
- move_to_end(key, last=True)#
Move an existing element to the end (or beginning if last is false).
Raise KeyError if the element does not exist.
- pop(key[, default]) 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(last=True)#
Remove and return a (key, value) pair from the dictionary.
Pairs are returned in LIFO order if last is true or FIFO order if false.
- 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:
SCons.Util.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.
- get()#
Retrieve the entire wrapped object
- class SCons.Builder.DictCmdGenerator(mapping=None, source_ext_match=True)[source]#
Bases:
SCons.Util.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.
- clear() None. Remove all items from od. #
- copy() a shallow copy of od #
- fromkeys(value=None)#
Create a new ordered 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 #
- move_to_end(key, last=True)#
Move an existing element to the end (or beginning if last is false).
Raise KeyError if the element does not exist.
- pop(key[, default]) 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(last=True)#
Remove and return a (key, value) pair from the dictionary.
Pairs are returned in LIFO order if last is true or FIFO order if false.
- 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.DictEmitter[source]#
Bases:
SCons.Util.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 od. #
- copy() a shallow copy of od #
- fromkeys(value=None)#
Create a new ordered 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 #
- move_to_end(key, last=True)#
Move an existing element to the end (or beginning if last is false).
Raise KeyError if the element does not exist.
- pop(key[, default]) 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(last=True)#
Remove and return a (key, value) pair from the dictionary.
Pairs are returned in LIFO order if last is true or FIFO order if false.
- 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:
collections.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:
collections.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 #
- 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
SCons.Builder._Null
SCons.CacheDir module#
CacheDir support
- class SCons.CacheDir.CacheDir(path)[source]#
Bases:
object
- _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_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.
- property hit_ratio: float#
- property misses: int#
- retrieve(node)[source]#
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.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=1, append=True, unique=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)[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)[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)[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=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='w', tstamp=False)[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.caller_trace(back=0)[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'>)[source]#
- SCons.Debug.dumpLoggedInstances(classes, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[source]#
- SCons.Debug.dump_caller_counts(file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)[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, **kw)[source]#
Initial public entry point for creating the default construction Environment.
After creating the environment, we overwrite our name (DefaultEnvironment) with the _fetch_DefaultEnvironment() function, which more efficiently returns the initialized default construction environment without checking for its existence.
(This function still exists with its _default_check because someone else (cough Script/__init__.py cough) may keep a reference to this function. So we can’t use the fully functional idiom of having the name originally be a something that only creates the construction environment and then overwrites the name.)
- class SCons.Defaults.NullCmdGenerator(cmd)[source]#
Bases:
object
This is a callable class that can be used in place of other command generators if you don’t want them to do anything.
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’)}”
- 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.
We use this to support “construction variables” in our string eval()s that actually stand in for methods–specifically, use of “RDirs” in call to _concat that should actually execute the “TARGET.RDirs” method. (We used to support this 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=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, **kw)[source]#
Returns the already-created default construction environment.
- SCons.Defaults._stripixes(prefix, itms, suffix, stripprefixes, stripsuffixes, env, c=None)[source]#
This is a wrapper around _concat()/_concat_ixes() that checks for the existence of prefixes or suffixes on list items and strips them where it finds them. This is used by tools (like the GNU linker) that need to turn something like ‘libfoo.a’ into ‘-lfoo’.
- 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.copy_func(dest, src, symlinks=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=True) str [source]#
strfunction for the Copy action function.
- SCons.Defaults.delete_func(dest, must_exist=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=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.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.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:
SCons.Environment.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.
- AddMethod(function, name=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.
- Append(**kw)[source]#
Append values to construction variables in an Environment.
The variable is created if it is not already present.
- AppendENVPath(name, newpath, envname='ENV', sep=':', delete_existing=False)[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=False, **kw)[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.
- 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.
- 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.
- Dump(key=None, format='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”)
- 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
- MergeFlags(args, unique=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()
.- 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)#
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=True)[source]#
Parse the result of running a command to update construction vars.
Use
function
to parse the output of runningcommand
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 asargs
. Iffunction
is omitted orNone
,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=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.
- Prepend(**kw)[source]#
Prepend values to construction variables in an Environment.
The variable is created if it is not already present.
- PrependENVPath(name, newpath, envname='ENV', sep=':', delete_existing=True)[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=False, **kw)[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.
- RemoveMethod(function)#
Removes the specified function’s MethodWrapper from the added_methods list, so we don’t re-bind it when making a clone.
- Replace(**kw)[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.
- 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).
- 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) SCons.Tool.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.
- _canonicalize(path)[source]#
Allow Dirs and strings beginning with # for top-relative.
Note this uses the current env’s fs (in self).
- _init_special()#
Initial the dispatch tables for special handling of special construction variables.
- _update(other)[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)[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) andParseConfig()
.- Raises
OSError – if the external command returned non-zero exit status.
- get(key, default=None)#
Emulates the get() method of dictionaries.
- get_factory(factory, default='File')[source]#
Return a factory function for creating Nodes for this construction environment.
- gvars()#
- items()#
Emulates the items() method of dictionaries.
- keys()#
Emulates the keys() method of dictionaries.
- lvars()#
- setdefault(key, default=None)#
Emulates the setdefault() method of dictionaries.
- subst(string, raw=0, target=None, source=None, conv=None, executor=None, overrides=False)#
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=0, target=None, source=None)#
- subst_list(string, raw=0, target=None, source=None, conv=None, executor=None, overrides=False)#
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, turning EntryProxies into Nodes and leaving Nodes (and other objects) as-is.
- subst_target_source(string, raw=0, target=None, source=None, conv=None, executor=None, overrides=False)#
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:
collections.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, method, name=None)[source]#
Bases:
SCons.Util.envs.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:
SCons.Environment.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)#
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)#
Append values to construction variables in an Environment.
The variable is created if it is not already present.
- AppendENVPath(name, newpath, envname='ENV', sep=':', delete_existing=False)#
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=False, **kw)#
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)#
- Clean(targets, files)#
- 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='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='.') list #
Return a list of all source files.
- Flatten(sequence)#
- GetBuildPath(files)#
- Glob(pattern, ondisk=True, source=False, strings=False, exclude=None)#
- Ignore(target, dependency)#
Ignore a dependency.
- Literal(string)#
- Local(*targets)#
- MergeFlags(args, unique=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()
.- 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=True)#
Parse the result of running a command to update construction vars.
Use
function
to parse the output of runningcommand
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 asargs
. Iffunction
is omitted orNone
,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=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)#
Prepend values to construction variables in an Environment.
The variable is created if it is not already present.
- PrependENVPath(name, newpath, envname='ENV', sep=':', delete_existing=True)#
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=False, **kw)#
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)#
Removes the specified function’s MethodWrapper from the added_methods list, so we don’t re-bind it when making a clone.
- Replace(**kw)[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)#
- 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)#
- Scanner(*args, **kw)#
- SetDefault(**kw)#
- 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) SCons.Tool.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=1)#
- 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)#
- _changed_content(dependency, target, prev_ni, repo_node=None)#
- _changed_source(dependency, target, prev_ni, repo_node=None)#
- _changed_timestamp_match(dependency, target, prev_ni, repo_node=None)#
- _changed_timestamp_newer(dependency, target, prev_ni, repo_node=None)#
- _changed_timestamp_then_content(dependency, target, prev_ni, repo_node=None)#
- _find_toolpath_dir(tp)#
- _gsm()#
- _init_special()#
Initial the dispatch tables for special handling of special construction variables.
- _update(other)[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)[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) andParseConfig()
.- Raises
OSError – if the external command returned non-zero exit status.
- get_CacheDir()#
- get_builder(name)#
Fetch the builder with the specified name from the environment.
- get_factory(factory, default='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).
- get_src_sig_type()#
- get_tgt_sig_type()#
- scanner_map_delete(kw=None)#
Delete the cached scanner map (if we need to).
- subst(string, raw=0, target=None, source=None, conv=None, executor=None, overrides=False)#
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=0, target=None, source=None)#
- subst_list(string, raw=0, target=None, source=None, conv=None, executor=None, overrides=False)#
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, turning EntryProxies into Nodes and leaving Nodes (and other objects) as-is.
- subst_target_source(string, raw=0, target=None, source=None, conv=None, executor=None, overrides=False)#
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.
- 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)[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=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()
.- 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)[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()[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) andParseConfig()
.- Raises
OSError – if the external command returned non-zero exit status.
- subst(string, raw=0, target=None, source=None, conv=None, executor=None, overrides=False)[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_list(string, raw=0, target=None, source=None, conv=None, executor=None, overrides=False)[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, turning EntryProxies into Nodes and leaving Nodes (and other objects) as-is.
- subst_target_source(string, raw=0, target=None, source=None, conv=None, executor=None, overrides=False)#
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.
- 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._delete_duplicates(l, keep_last)[source]#
Delete duplicates from a sequence, keeping the first or last.
- SCons.Environment._null#
alias of
SCons.Environment._Null
SCons.Errors module#
SCons exception classes.
Used to handle internal and user errors in SCons.
- exception SCons.Errors.BuildError(node=None, errstr='Unknown error', status=2, exitstatus=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 asstatus
, 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 beNone
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.
- 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.
- 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#
- _memo#
- _unchanged_sources_list#
- _unchanged_targets_list#
- action_list#
- add_batch(targets, sources)[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_sources(sources)[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#
- env#
- get_action_side_effects()[source]#
Returns all side effects for all batches of this Executor used by the underlying Action.
- 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_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_timestamp()[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.
- lvars#
- overridelist#
- post_actions#
- pre_actions#
- prepare()[source]#
Preparatory checks for whether this Executor can go ahead and (try to) build its targets.
- 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#
- _unchanged_sources_list#
- _unchanged_targets_list#
- action_list#
- batches#
- builder_kw#
- env#
- lvars#
- overridelist#
- post_actions#
- pre_actions#
- class SCons.Executor.NullEnvironment(*args, **kwargs)[source]#
Bases:
SCons.Util.types.Null
- SCons = <module 'SCons' from '/Users/bdbaddog/devel/scons/git/as_scons/SCons/__init__.py'>#
- _CacheDir = <SCons.CacheDir.CacheDir object>#
- _CacheDir_path = None#
- class SCons.Executor.TSList(func)[source]#
Bases:
collections.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)#
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:
SCons.Memoize.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)[source]#
Counts whether the computed key value is already present in the memoization dictionary (a hit) or not (a miss).
- display()#
- 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:
SCons.Memoize.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)[source]#
Counts whether the memoized value has already been set (a hit) or not (a miss).
- display()#
- 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.
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)#
Returns the cached _PathList object for the specified pathlist, creating and caching a new object as necessary.
- 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.CheckCXXHeader(context, header, include_quotes='""')[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.
- SCons.SConf.CheckHeader(context, header, include_quotes='<>', language=None)[source]#
A test for a C or C++ header file.
- SCons.SConf.CheckLib(context, library=None, symbol='main', header=None, language=None, autoadd=True, append=True, unique=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=True, append=True, unique=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)[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.
- exception SCons.SConf.ConfigureCacheError(target)[source]#
Bases:
SCons.SConf.SConfError
Raised when a use explicitely requested the cache feature, but the test is run the first time.
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.SConf.ConfigureDryRunError(target)[source]#
Bases:
SCons.SConf.SConfError
Raised when a file or directory needs to be updated during a Configure process, but the user requested a dry-run
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- SCons.SConf.CreateConfigHBuilder(env)[source]#
Called if necessary just before the building targets phase begins.
- class SCons.SConf.SConfBase(env, custom_tests={}, conf_dir='$CONFIGUREDIR', log_file='$CONFIGURELOG', config_h=None, _depth=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)[source]#
Adds test_class to this SConf instance. It can be called with self.test_name(…)
- BuildNodes(nodes)[source]#
Tries to build the given nodes immediately. Returns 1 on success, 0 on error.
- Define(name, value=None, comment=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).
- TryAction(action, text=None, extension='')[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='')[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).
- TryLink(text, extension)[source]#
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).
- _startup()[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:
SCons.Node.FS.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)#
Restore the attributes from a pickled state.
- bact#
- bactsig#
- bdepends#
- bdependsigs#
- bimplicit#
- bimplicitsigs#
- bsources#
- bsourcesigs#
- convert_from_sconsign(dir, name)#
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()#
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=0)#
- merge(other)#
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()#
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#
- string#
- class SCons.SConf.SConfBuildTask(tm, targets, top, node)[source]#
Bases:
SCons.Taskmaster.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()#
- display(message)[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)[source]#
Logs the original builder messages, given the SConfBuildInfo instance bi.
- exc_clear()#
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)#
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()#
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()#
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()#
Called when the task has been successfully executed and the Taskmaster instance doesn’t want to call the Node’s callback methods.
- fail_continue()#
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()#
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()#
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()#
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()[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()#
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()[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()#
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='node')#
- exception SCons.SConf.SConfError(msg)[source]#
Bases:
SCons.Errors.UserError
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.SConf.SConfWarning[source]#
Bases:
SCons.Warnings.SConsWarning
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- SCons.SConf.SetCacheMode(mode)[source]#
Set the Configure cache mode. mode must be one of “auto”, “force”, or “cache”.
- SCons.SConf.SetProgressDisplay(display)[source]#
Set the progress display to use (called from SCons.Script)
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.
- class SCons.SConsign.DB(dir)[source]#
Bases:
SCons.SConsign.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)#
- do_not_store_info(filename, node)#
- get_entry(filename)#
Fetch the specified entry attribute.
- merge()#
- set_entry(filename, obj)#
Set the entry.
- store_info(filename, node)#
- class SCons.SConsign.Dir(fp=None, dir=None)[source]#
Bases:
SCons.SConsign.Base
- do_not_set_entry(filename, obj)#
- do_not_store_info(filename, node)#
- get_entry(filename)#
Fetch the specified entry attribute.
- merge()#
- set_entry(filename, obj)#
Set the entry.
- store_info(filename, node)#
- class SCons.SConsign.DirFile(dir)[source]#
Bases:
SCons.SConsign.Dir
Encapsulates reading and writing a per-directory .sconsign file.
- do_not_set_entry(filename, obj)#
- do_not_store_info(filename, node)#
- get_entry(filename)#
Fetch the specified entry attribute.
- merge()#
- set_entry(filename, obj)#
Set the entry.
- store_info(filename, node)#
- write(sync=1)[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)[source]#
Arrange for all signatures to be stored in a global .sconsign.db* file.
- SCons.SConsign.ForDirectory#
alias of
SCons.SConsign.DB
- SCons.SConsign.Reset()[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#
- current_version_id = 2#
- ninfo#
SCons.Subst module#
SCons string substitution.
- class SCons.Subst.CmdStringHolder(cmd, literal=None)[source]#
Bases:
collections.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.
- 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:
collections.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_to_current_word(x)[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 #
- 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)[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
- next_line()[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.
- 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.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.
- 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()#
- 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.
- 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.
- 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:
collections.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.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.scons_subst(strSubst, env, mode=1, target=None, source=None, gvars={}, lvars={}, conv=None, overrides=False)[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=False)[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.Util module#
SCons utility functions
This package contains routines for use by other parts of SCons.
- class SCons.Util.CLVar(initlist=None)[source]#
Bases:
collections.UserList
A container for command-line construction variables.
Forces the use of a list of strings intended as command-line arguments. Like
collections.UserList
, but the argument passed to the initializter will be processed by theSplit()
function, which includes special handling for string types: they will be split into a list of words, not coereced directly to a list. The same happens if a string is added to aCLVar
, which allows doing the right thing with bothAppend()
/Prepend()
methods, as well as with pure Python addition, regardless of whether adding a list or a string to a construction variable.Side effect: spaces will be stripped from individual string arguments. If you need spaces preserved, pass strings containing spaces inside a list argument.
>>> u = UserList("--some --opts and args") >>> print(len(u), repr(u)) 22 ['-', '-', 's', 'o', 'm', 'e', ' ', '-', '-', 'o', 'p', 't', 's', ' ', 'a', 'n', 'd', ' ', 'a', 'r', 'g', 's'] >>> c = CLVar("--some --opts and args") >>> print(len(c), repr(c)) 4 ['--some', '--opts', 'and', 'args'] >>> c += " strips spaces " >>> print(len(c), repr(c)) 6 ['--some', '--opts', 'and', 'args', 'strips', 'spaces']
- _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.Util.Delegate(attribute)[source]#
Bases:
object
A Python Descriptor class that delegates attribute fetches to an underlying wrapped subject of a Proxy. Typical use:
class Foo(Proxy): __str__ = Delegate('__str__')
- class SCons.Util.DispatchingFormatter(formatters, default_formatter)[source]#
Bases:
logging.Formatter
- converter()#
- localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
tm_sec,tm_wday,tm_yday,tm_isdst)
Convert seconds since the Epoch to a time tuple expressing local time. When ‘seconds’ is not passed in, convert the current time instead.
- default_msec_format = '%s,%03d'#
- default_time_format = '%Y-%m-%d %H:%M:%S'#
- format(record)[source]#
Format the specified record as text.
The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.
- formatException(ei)#
Format and return the specified exception information as a string.
This default implementation just uses traceback.print_exception()
- formatMessage(record)#
- formatStack(stack_info)#
This method is provided as an extension point for specialized formatting of stack information.
The input data is a string as returned from a call to
traceback.print_stack()
, but with the last trailing newline removed.The base implementation just returns the value passed in.
- formatTime(record, datefmt=None)#
Return the creation time of the specified LogRecord as formatted text.
This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the ‘converter’ attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the ‘converter’ attribute in the Formatter class.
- usesTime()#
Check if the format uses the creation time of the record.
- class SCons.Util.DisplayEngine[source]#
Bases:
object
A callable class used to display SCons messages.
- print_it = True#
- SCons.Util.IDX(n) bool [source]#
Generate in index into strings from the tree legends.
These are always a choice between two, so bool works fine.
- class SCons.Util.LogicalLines(fileobj)[source]#
Bases:
object
Wrapper class for the logical_lines method.
Allows us to read all “logical” lines at once from a given file object.
- class SCons.Util.NodeList(initlist=None)[source]#
Bases:
collections.UserList
A list of Nodes with special attribute retrieval.
Unlike an ordinary list, access to a member’s attribute returns a NodeList containing the same attribute for each member. Although this can hold any object, it is intended for use when processing Nodes, where fetching an attribute of each member is very commone, for example getting the content signature of each node. The term “attribute” here includes the string representation.
>>> someList = NodeList([' foo ', ' bar ']) >>> someList.strip() ['foo', 'bar']
- __getattr__(name) SCons.Util.NodeList [source]#
Returns a NodeList of name from each member.
- _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.Util.Proxy(subject)[source]#
Bases:
object
A simple generic Proxy class, forwarding all calls to subject.
This means you can take an object, let’s call it ‘obj_a, and wrap it in this Proxy class, with a statement like this:
proxy_obj = Proxy(obj_a)
Then, if in the future, you do something like this:
x = proxy_obj.var1
since the
Proxy
class does not have avar1
attribute (but presumably objA does), the request actually is equivalent to saying:x = obj_a.var1
Inherit from this class to create a Proxy.
With Python 3.5+ this does not work transparently for
Proxy
subclasses that use special .__*__() method names, because those names are now bound to the class, not the individual instances. You now need to know in advance which special method names you want to pass on to the underlying Proxy object, and specifically delegate their calls like this:class Foo(Proxy): __str__ = Delegate('__str__')
- SCons.Util.RegError#
alias of
SCons.Util._NoError
- class SCons.Util.Selector[source]#
Bases:
collections.OrderedDict
A callable ordered dictionary that maps file suffixes to dictionary values. We preserve the order in which items are added so that
get_suffix()
calls always return the first suffix added.- clear() None. Remove all items from od. #
- copy() a shallow copy of od #
- fromkeys(value=None)#
Create a new ordered 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 #
- move_to_end(key, last=True)#
Move an existing element to the end (or beginning if last is false).
Raise KeyError if the element does not exist.
- pop(key[, default]) 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(last=True)#
Remove and return a (key, value) pair from the dictionary.
Pairs are returned in LIFO order if last is true or FIFO order if false.
- 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 #
- SCons.Util.Split(arg) list [source]#
Returns a list of file names or other objects.
If arg is a string, it will be split on strings of white-space characters within the string. If arg is already a list, the list will be returned untouched. If arg is any other type of object, it will be returned as a list containing just the object.
>>> print(Split(" this is a string ")) ['this', 'is', 'a', 'string'] >>> print(Split(["stringlist", " preserving ", " spaces "])) ['stringlist', ' preserving ', ' spaces ']
- class SCons.Util.Unbuffered(file)[source]#
Bases:
object
A proxy that wraps a file object, flushing after every write.
Delegates everything else to the wrapped object.
- class SCons.Util.UniqueList(initlist=None)[source]#
Bases:
collections.UserList
A list which maintains uniqueness.
Uniquing is lazy: rather than being assured on list changes, it is fixed up on access by those methods which need to act on a unique list to be correct. That means things like “in” don’t have to eat the uniquing time.
- __make_unique()#
- _abc_impl = <_abc._abc_data object>#
- clear() None -- remove all items from S #
- copy()#
- index(value[, start[, stop]]) integer -- return first index of value. [source]#
Raises ValueError if the value is not present.
Supporting start and stop arguments is optional, but recommended.
- 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.
- SCons.Util.WhereIs(file, path=None, pathext=None, reject=None) Optional[str] [source]#
Return the path to an executable that matches file.
Searches the given path for file, respecting any filename extensions pathext (on the Windows platform only), and returns the full path to the matching command. If no command is found, return
None
.If path is not specified,
os.environ[PATH]
is used. If pathext is not specified,os.environ[PATHEXT]
is used. Will not select any path name or names in the optional reject list.
- exception SCons.Util._NoError[source]#
Bases:
Exception
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- SCons.Util.adjustixes(fname, pre, suf, ensure_suffix=False) str [source]#
Adjust filename prefixes and suffixes as needed.
Add prefix to fname if specified. Add suffix to fname if specified and if ensure_suffix is
True
- SCons.Util.containsAll(s, pat) bool [source]#
Check whether string s contains ALL of the items in pat.
- SCons.Util.containsAny(s, pat) bool [source]#
Check whether string s contains ANY of the items in pat.
- SCons.Util.do_flatten(sequence, result, isinstance=<built-in function isinstance>, StringTypes=(<class 'str'>, <class 'collections.UserString'>), SequenceTypes=(<class 'list'>, <class 'tuple'>, <class 'collections.deque'>, <class 'collections.UserList'>, <class 'collections.abc.MappingView'>))[source]#
- SCons.Util.flatten(obj, isinstance=<built-in function isinstance>, StringTypes=(<class 'str'>, <class 'collections.UserString'>), SequenceTypes=(<class 'list'>, <class 'tuple'>, <class 'collections.deque'>, <class 'collections.UserList'>, <class 'collections.abc.MappingView'>), do_flatten=<function do_flatten>) list [source]#
Flatten a sequence to a non-nested list.
Converts either a single scalar or a nested sequence to a non-nested list. Note that
flatten()
considers strings to be scalars instead of sequences like pure Python would.
- SCons.Util.flatten_sequence(sequence, isinstance=<built-in function isinstance>, StringTypes=(<class 'str'>, <class 'collections.UserString'>), SequenceTypes=(<class 'list'>, <class 'tuple'>, <class 'collections.deque'>, <class 'collections.UserList'>, <class 'collections.abc.MappingView'>), do_flatten=<function do_flatten>) list [source]#
Flatten a sequence to a non-nested list.
Same as
flatten()
, but it does not handle the single scalar case. This is slightly more efficient when one knows that the sequence to flatten can not be a scalar.
- SCons.Util.get_native_path(path) str [source]#
Transform an absolute path into a native path for the system.
In Cygwin, this converts from a Cygwin path to a Windows path, without regard to whether path refers to an existing file system object. For other platforms, path is unchanged.
- SCons.Util.make_path_relative(path) str [source]#
Converts an absolute path name to a relative pathname.
- SCons.Util.print_tree(root, child_func, prune=0, showtags=False, margin=[0], visited=None, lastChild: bool = False, singleLineDraw: bool = False) None [source]#
Print a tree of nodes.
This is like func:render_tree, except it prints lines directly instead of creating a string representation in memory, so that huge trees can be handled.
- Parameters
root – the root node of the tree
child_func – the function called to get the children of a node
prune – don’t visit the same node twice
showtags – print status information to the left of each node line
margin – the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe.
visited – a dictionary of visited nodes in the current branch if prune is 0, or in the whole tree if prune is 1.
lastChild – this is the last leaf of a branch
singleLineDraw – use line-drawing characters rather than ASCII.
- SCons.Util.render_tree(root, child_func, prune=0, margin=[0], visited=None) str [source]#
Render a tree of nodes into an ASCII tree view.
- Parameters
root – the root node of the tree
child_func – the function called to get the children of a node
prune – don’t visit the same node twice
margin – the format of the left margin to use for children of root. 1 results in a pipe, and 0 results in no pipe.
visited – a dictionary of visited nodes in the current branch if prune is 0, or in the whole tree if prune is 1.
- SCons.Util.sanitize_shell_env(execution_env: dict) dict [source]#
Sanitize all values in execution_env
The execution environment (typically comes from (env[‘ENV’]) is propagated to the shell, and may need to be cleaned first.
- Parameters
execution_env – The shell environment variables to be propagated
shell. (to the spawned) –
- Returns
sanitized dictionary of env variables (similar to what you’d get from
os.environ
)
- SCons.Util.silent_intern(x)[source]#
Perform
sys.intern
on the passed argument and return the result. If the input is ineligible for interning the original argument is returned and no exception is thrown.
- SCons.Util.splitext(path) tuple [source]#
Split path into a (root, ext) pair.
Same as
os.path.splitext
but faster.
- SCons.Util.unique(seq)[source]#
Return a list of the elements in seq without duplicates, ignoring order.
>>> mylist = unique([1, 2, 3, 1, 2, 3]) >>> print(sorted(mylist)) [1, 2, 3] >>> mylist = unique("abcabc") >>> print(sorted(mylist)) ['a', 'b', 'c'] >>> mylist = unique(([1, 2], [2, 3], [1, 2])) >>> print(sorted(mylist)) [[1, 2], [2, 3]]
For best speed, all sequence elements should be hashable. Then unique() will usually work in linear time.
If not possible, the sequence elements should enjoy a total ordering, and if list(s).sort() doesn’t raise TypeError it’s assumed that they do enjoy a total ordering. Then unique() will usually work in O(N*log2(N)) time.
If that’s not possible either, the sequence elements must support equality-testing. Then unique() will usually work in quadratic time.
SCons.Warnings module#
The SCons warnings framework.
- exception SCons.Warnings.CacheCleanupErrorWarning[source]#
Bases:
SCons.Warnings.SConsWarning
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.CacheVersionWarning[source]#
Bases:
SCons.Warnings.WarningOnByDefault
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.CacheWriteErrorWarning[source]#
Bases:
SCons.Warnings.SConsWarning
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.CorruptSConsignWarning[source]#
Bases:
SCons.Warnings.WarningOnByDefault
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.DependencyWarning[source]#
Bases:
SCons.Warnings.SConsWarning
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.DeprecatedDebugOptionsWarning[source]#
Bases:
SCons.Warnings.MandatoryDeprecatedWarning
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.DeprecatedMissingSConscriptWarning[source]#
Bases:
SCons.Warnings.DeprecatedWarning
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.DeprecatedOptionsWarning[source]#
Bases:
SCons.Warnings.MandatoryDeprecatedWarning
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.DeprecatedSourceCodeWarning[source]#
Bases:
SCons.Warnings.FutureDeprecatedWarning
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.DeprecatedWarning[source]#
Bases:
SCons.Warnings.SConsWarning
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.DevelopmentVersionWarning[source]#
Bases:
SCons.Warnings.WarningOnByDefault
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.DuplicateEnvironmentWarning[source]#
Bases:
SCons.Warnings.WarningOnByDefault
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.FortranCxxMixWarning[source]#
Bases:
SCons.Warnings.LinkWarning
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.FutureDeprecatedWarning[source]#
Bases:
SCons.Warnings.SConsWarning
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.FutureReservedVariableWarning[source]#
Bases:
SCons.Warnings.WarningOnByDefault
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.LinkWarning[source]#
Bases:
SCons.Warnings.WarningOnByDefault
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.MandatoryDeprecatedWarning[source]#
Bases:
SCons.Warnings.DeprecatedWarning
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.MisleadingKeywordsWarning[source]#
Bases:
SCons.Warnings.WarningOnByDefault
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.MissingSConscriptWarning[source]#
Bases:
SCons.Warnings.WarningOnByDefault
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.NoObjectCountWarning[source]#
Bases:
SCons.Warnings.WarningOnByDefault
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.NoParallelSupportWarning[source]#
Bases:
SCons.Warnings.WarningOnByDefault
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.PythonVersionWarning[source]#
Bases:
SCons.Warnings.DeprecatedWarning
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.ReservedVariableWarning[source]#
Bases:
SCons.Warnings.WarningOnByDefault
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.SConsWarning[source]#
Bases:
SCons.Errors.UserError
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.StackSizeWarning[source]#
Bases:
SCons.Warnings.WarningOnByDefault
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.TargetNotBuiltWarning[source]#
Bases:
SCons.Warnings.SConsWarning
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.TaskmasterNeedsExecuteWarning[source]#
Bases:
SCons.Warnings.DeprecatedWarning
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.ToolQtDeprecatedWarning[source]#
Bases:
SCons.Warnings.DeprecatedWarning
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.VisualCMissingWarning[source]#
Bases:
SCons.Warnings.WarningOnByDefault
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.VisualStudioMissingWarning[source]#
Bases:
SCons.Warnings.SConsWarning
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.VisualVersionMismatch[source]#
Bases:
SCons.Warnings.WarningOnByDefault
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception SCons.Warnings.WarningOnByDefault[source]#
Bases:
SCons.Warnings.SConsWarning
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- SCons.Warnings.enableWarningClass(clazz)[source]#
Enables all warnings of type clazz or derived from clazz.
- SCons.Warnings.process_warn_strings(arguments)[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)[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.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)#
- class SCons.cpp.DumbPreProcessor(*args, **kw)[source]#
Bases:
SCons.cpp.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)#
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)#
- do_define(t)#
Default handling of a #define line.
- do_elif(t)#
Default handling of a #elif line.
- do_else(t)#
Default handling of a #else line.
- do_endif(t)#
Default handling of a #endif line.
- do_if(t)#
Default handling of a #if line.
- do_ifdef(t)#
Default handling of a #ifdef line.
- do_ifndef(t)#
Default handling of a #ifndef line.
- do_import(t)#
Default handling of a #import line.
- do_include(t)#
Default handling of a #include line.
- do_include_next(t)#
Default handling of a #include line.
- do_nothing(t)#
Null method for when we explicitly want the action for a specific preprocessor directive to do nothing.
- do_undef(t)#
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)#
- 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()#
Pops the previous dispatch table off the stack and makes it the current one.
- save()#
Pushes the current dispatch table on the stack and re-initializes the current dispatch table to the default.
- scons_current_file(t)#
- start_handling_includes(t=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)#
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.
- class SCons.cpp.PreProcessor(current='.', cpppath=(), dict={}, all=0, depth=- 1)[source]#
Bases:
object
The main workhorse class for handling C pre-processing.
- _do_if_else_condition(condition)[source]#
Common logic for evaluating the conditions on #if, #ifdef and #ifndef lines.
- do_include_next(t)#
Default handling of a #include line.
- do_nothing(t)[source]#
Null method for when we explicitly want the action for a specific preprocessor directive to do nothing.
- 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.
- 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.
- save()[source]#
Pushes the current dispatch table on the stack and re-initializes the current dispatch table to the default.
- start_handling_includes(t=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)[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.
- class SCons.dblite.dblite(file_base_name, flag, mode)[source]#
Bases:
object
Squirrel away references to the functions in various modules that we’ll use when our __del__() method calls our sync() method during shutdown. We might get destroyed when Python is in the midst of tearing down the different modules we import in an essentially arbitrary order, and some of the various modules’s global attributes may already be wiped out from under us.
- See the discussion at:
http://mail.python.org/pipermail/python-bugs-list/2003-March/016877.html
- _open(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.getpreferredencoding(False) 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)
‘U’
universal newline mode (deprecated)
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.
‘U’ mode is deprecated and will raise an exception in future versions of Python. It has no effect in Python 3. Use newline to control universal newlines mode.
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.
- _os_chmod(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.
- _os_chown(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.
- _os_replace(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#
- _shutil_copyfile(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.
- _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.
SCons.exitfuncs module#
Register functions which are executed when SCons exits for any reason.