SCons.Script package#
Module contents#
The main() function used by the scons script.
Architecturally, this is the scons script, and will likely only be called from the external “scons” wrapper. Consequently, anything here should not be, or be considered, part of the build engine. If it’s something that we expect other software to want to use, it should go in some other module. If it’s specific to the “scons” script invocation, it goes here.
- SCons.Script.HelpFunction(text, append: bool = False, local_only: bool = False) None[source]#
The implementaion of the the
Helpmethod.See
Help().Changed in version 4.6.0: The keep_local parameter was added.
Changed in version 4.9.0: The keep_local parameter was renamed local_only to match manpage
- class SCons.Script.TargetList(initlist=None)[source]#
Bases:
UserList- _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.Script._Add_Targets(tlist: list[str]) None[source]#
Add value(s) to
COMMAND_LINE_TARGETSandBUILD_TARGETS.
- SCons.Script._Get_Default_Targets(d, fs)#
- SCons.Script._Remove_Argument(aarg: str) None[source]#
Remove aarg from
ARGLISTandARGUMENTS.Used to remove a variables-style argument that is no longer valid. This can happpen because the command line is processed once early, before we see any
SCons.Script.Main.AddOption()calls, so we could not recognize it belongs to an option and is not a standalone variable=value argument.Added in version 4.10.0.
- SCons.Script._Remove_Target(targ: str) None[source]#
Remove targ from
BUILD_TARGETSandCOMMAND_LINE_TARGETS.Used to remove a target that is no longer valid. This can happpen because the command line is processed once early, before we see any
SCons.Script.Main.AddOption()calls, so we could not recognize it belongs to an option and is not a standalone target argument.Since we are “correcting an error”, we also have to fix up the internal
_build_plus_defaultlist.Added in version 4.10.0.
Submodules#
SCons.Script.Interactive module#
SCons interactive mode.
- class SCons.Script.Interactive.SConsInteractiveCmd(**kw)[source]#
Bases:
Cmdbuild [TARGETS] Build the specified TARGETS and their dependencies. ‘b’ is a synonym. clean [TARGETS] Clean (remove) the specified TARGETS and their dependencies. ‘c’ is a synonym. exit Exit SCons interactive mode. help [COMMAND] Prints help for the specified COMMAND. ‘h’ and ‘?’ are synonyms. shell [COMMANDLINE] Execute COMMANDLINE in a subshell. ‘sh’ and ‘!’ are synonyms. version Prints SCons version information.
- cmdloop(intro=None)#
Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument.
- columnize(list, displaywidth=80)#
Display a list of strings as a compact set of columns.
Each column is only as wide as necessary. Columns are separated by two spaces (one was not legible enough).
- complete(text, state)#
Return the next possible completion for ‘text’.
If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions.
- complete_help(*args)#
- completedefault(*ignored)#
Method called to complete an input line when no command-specific complete_*() method is available.
By default, it returns an empty list.
- completenames(text, *ignored)#
- default(argv) None[source]#
Called on an input line when the command prefix is not recognized.
If this method is not overridden, it prints an error message and returns.
- do_build(argv) None[source]#
build [TARGETS] Build the specified TARGETS and their dependencies. ‘b’ is a synonym.
- do_clean(argv)[source]#
clean [TARGETS] Clean (remove) the specified TARGETS and their dependencies. ‘c’ is a synonym.
- do_help(argv) None[source]#
help [COMMAND] Prints help for the specified COMMAND. ‘h’ and ‘?’ are synonyms.
- do_shell(argv) None[source]#
shell [COMMANDLINE] Execute COMMANDLINE in a subshell. ‘sh’ and ‘!’ are synonyms.
- doc_header = 'Documented commands (type help <topic>):'#
- doc_leader = ''#
- emptyline()#
Called when an empty line is entered in response to the prompt.
If this method is not overridden, it repeats the last nonempty command entered.
- get_names()#
- identchars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'#
- intro = None#
- lastcmd = ''#
- misc_header = 'Miscellaneous help topics:'#
- nohelp = '*** No help on %s'#
- onecmd(line)[source]#
Interpret the argument as though it had been typed in response to the prompt.
This may be overridden, but should not normally need to be; see the precmd() and postcmd() methods for useful execution hooks. The return value is a flag indicating whether interpretation of commands by the interpreter should stop.
- parseline(line)#
Parse the line into a command name and a string containing the arguments. Returns a tuple containing (command, args, line). ‘command’ and ‘args’ may be None if the line couldn’t be parsed.
- postcmd(stop, line)#
Hook method executed just after a command dispatch is finished.
- postloop()#
Hook method executed once when the cmdloop() method is about to return.
- precmd(line)#
Hook method executed just before the command line is interpreted, but after the input prompt is generated and issued.
- preloop()#
Hook method executed once when the cmdloop() method is called.
- print_topics(header, cmds, cmdlen, maxcol)#
- prompt = '(Cmd) '#
- ruler = '='#
- synonyms = {'b': 'build', 'c': 'clean', 'h': 'help', 'scons': 'build', 'sh': 'shell'}#
- undoc_header = 'Undocumented commands:'#
- use_rawinput = 1#
SCons.Script.Main module#
The main() function used by the scons script.
Architecturally, this is the scons script, and will likely only be called from the external “scons” wrapper. Consequently, anything here should not be, or be considered, part of the build engine. If it’s something that we expect other software to want to use, it should go in some other module. If it’s specific to the “scons” script invocation, it goes here.
- SCons.Script.Main.AddOption(*args, **kw) SConsOption[source]#
Add a local option to the option parser - Public API.
If the SCons-specific settable kwarg is true (default
False), the option will allow callingSetOption().Changed in version 4.8.0: The settable parameter added to allow including the new option in the table of options eligible to use
SetOption().
- class SCons.Script.Main.BuildTask(tm, targets, top, node)[source]#
Bases:
OutOfDateTaskAn SCons build task.
- LOGGER = None#
- _abc_impl = <_abc._abc_data object>#
- _exception_raise()#
Raises a pending exception that was recorded while getting a Task ready for execution.
- _no_exception_to_raise() None#
- display(message) None[source]#
Hook to allow the calling interface to display a message.
This hook gets called as part of preparing a task for execution (that is, a Node to be built). As part of figuring out what Node should be built next, the actual target list may be altered, along with a message describing the alteration. The calling interface can subclass Task and provide a concrete implementation of this method to see those messages.
- exc_clear() None#
Clears any recorded exception.
This also changes the “exception_raise” attribute to point to the appropriate do-nothing method.
- exc_info()#
Returns info about a recorded exception.
- exception_set(exception=None) None#
Records an exception to be raised at the appropriate time.
This also changes the “exception_raise” attribute to point to the method that will, in fact
- execute() None[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()[source]#
Called when the task has been successfully executed and the Taskmaster instance wants to call the Node’s callback methods.
This may have been a do-nothing operation (to preserve build order), so we must check the node’s state before deciding whether it was “built”, in which case we call the appropriate Node method. In any event, we always call “visited()”, which will handle any post-visit actions that must take place regardless of whether or not the target was an actual built target or a source Node.
- executed_with_callbacks() None#
Called when the task has been successfully executed and the Taskmaster instance wants to call the Node’s callback methods.
This may have been a do-nothing operation (to preserve build order), so we must check the node’s state before deciding whether it was “built”, in which case we call the appropriate Node method. In any event, we always call “visited()”, which will handle any post-visit actions that must take place regardless of whether or not the target was an actual built target or a source Node.
- executed_without_callbacks() None#
Called when the task has been successfully executed and the Taskmaster instance doesn’t want to call the Node’s callback methods.
- fail_continue() None#
Explicit continue-the-build failure.
This sets failure status on the target nodes and all of their dependent parent nodes.
Note: Although this function is normally invoked on nodes in the executing state, it might also be invoked on up-to-date nodes when using Configure().
- fail_stop() None#
Explicit stop-the-build failure.
This sets failure status on the target nodes and all of their dependent parent nodes.
Note: Although this function is normally invoked on nodes in the executing state, it might also be invoked on up-to-date nodes when using Configure().
- failed() None[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_all() None#
Marks all targets in a task ready for execution.
This is used when the interface needs every target Node to be visited–the canonical example being the “scons -c” option.
- make_ready_current()#
Marks all targets in a task ready for execution if any target is not current.
This is the default behavior for building only what’s necessary.
- needs_execute() bool[source]#
Returns True (indicating this Task should be executed) if this Task’s target state indicates it needs executing, which has already been determined by an earlier up-to-date check.
- postprocess() None[source]#
Post-processes a task after it’s been executed.
This examines all the targets just built (or not, we don’t care if the build was successful, or even if there was no build because everything was up-to-date) to see if they have any waiting parent Nodes, or Nodes waiting on a common side effect, that can be put back on the candidates list.
- prepare()[source]#
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.
- progress = None#
- trace_message(node, description: str = 'node') None#
- class SCons.Script.Main.CleanTask(tm, targets, top, node)[source]#
Bases:
AlwaysTaskAn SCons clean task.
- LOGGER = None#
- _abc_impl = <_abc._abc_data object>#
- _exception_raise()#
Raises a pending exception that was recorded while getting a Task ready for execution.
- _no_exception_to_raise() None#
- display(message) None#
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.
- exc_clear() None#
Clears any recorded exception.
This also changes the “exception_raise” attribute to point to the appropriate do-nothing method.
- exc_info()#
Returns info about a recorded exception.
- exception_set(exception=None) None#
Records an exception to be raised at the appropriate time.
This also changes the “exception_raise” attribute to point to the method that will, in fact
- execute() None#
Called to execute the task.
This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in prepare(), executed() or failed().
- executed() None#
Called when the task has been successfully executed and the Taskmaster instance doesn’t want to call the Node’s callback methods.
- executed_with_callbacks() None#
Called when the task has been successfully executed and the Taskmaster instance wants to call the Node’s callback methods.
This may have been a do-nothing operation (to preserve build order), so we must check the node’s state before deciding whether it was “built”, in which case we call the appropriate Node method. In any event, we always call “visited()”, which will handle any post-visit actions that must take place regardless of whether or not the target was an actual built target or a source Node.
- executed_without_callbacks() None#
Called when the task has been successfully executed and the Taskmaster instance doesn’t want to call the Node’s callback methods.
- fail_continue() None#
Explicit continue-the-build failure.
This sets failure status on the target nodes and all of their dependent parent nodes.
Note: Although this function is normally invoked on nodes in the executing state, it might also be invoked on up-to-date nodes when using Configure().
- fail_stop() None#
Explicit stop-the-build failure.
This sets failure status on the target nodes and all of their dependent parent nodes.
Note: Although this function is normally invoked on nodes in the executing state, it might also be invoked on up-to-date nodes when using Configure().
- failed() None#
Default action when a task fails: stop the build.
Note: Although this function is normally invoked on nodes in the executing state, it might also be invoked on up-to-date nodes when using Configure().
- get_target()#
Fetch the target being built or updated by this task.
- make_ready() None#
Marks all targets in a task ready for execution.
This is used when the interface needs every target Node to be visited–the canonical example being the “scons -c” option.
- make_ready_all() None#
Marks all targets in a task ready for execution.
This is used when the interface needs every target Node to be visited–the canonical example being the “scons -c” option.
- make_ready_current()#
Marks all targets in a task ready for execution if any target is not current.
This is the default behavior for building only what’s necessary.
- needs_execute() bool#
Always returns True (indicating this Task should always be executed).
Subclasses that need this behavior (as opposed to the default of only executing Nodes that are out of date w.r.t. their dependencies) can use this as follows:
- class MyTaskSubclass(SCons.Taskmaster.Task):
needs_execute = SCons.Taskmaster.AlwaysTask.needs_execute
- postprocess() None#
Post-processes a task after it’s been executed.
This examines all the targets just built (or not, we don’t care if the build was successful, or even if there was no build because everything was up-to-date) to see if they have any waiting parent Nodes, or Nodes waiting on a common side effect, that can be put back on the candidates list.
- prepare() None[source]#
Called just before the task is executed.
This is mainly intended to give the target Nodes a chance to unlink underlying files and make all necessary directories before the Action is actually called to build the targets.
- trace_message(node, description: str = 'node') None#
- SCons.Script.Main.DebugOptions(json: str | None = None) None[source]#
Specify options to SCons debug logic - Public API.
Currently only json is supported, which changes the JSON file written to if the
--debug=jsoncommand-line option is specified to the value supplied.Added in version 4.6.0.
- class SCons.Script.Main.FakeOptionParser[source]#
Bases:
objectA do-nothing option parser, used for the initial OptionsParser value.
During normal SCons operation, the OptionsParser is created right away by the main() function. Certain test scripts however, can introspect on different Tool modules, the initialization of which can try to add a new, local option to an otherwise uninitialized OptionsParser object. This allows that introspection to happen without blowing up.
- add_local_option(*args, **kw) SConsOption[source]#
- values = <SCons.Script.Main.FakeOptionParser.FakeOptionValues object>#
- class SCons.Script.Main.Progressor(obj, interval: int = 1, file=None, overwrite: bool = False)[source]#
Bases:
object- count = 0#
- prev = ''#
- target_string = '$TARGET'#
- class SCons.Script.Main.QuestionTask(tm, targets, top, node)[source]#
Bases:
AlwaysTaskAn SCons task for the -q (question) option.
- LOGGER = None#
- _abc_impl = <_abc._abc_data object>#
- _exception_raise()#
Raises a pending exception that was recorded while getting a Task ready for execution.
- _no_exception_to_raise() None#
- display(message) None#
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.
- exc_clear() None#
Clears any recorded exception.
This also changes the “exception_raise” attribute to point to the appropriate do-nothing method.
- exc_info()#
Returns info about a recorded exception.
- exception_set(exception=None) None#
Records an exception to be raised at the appropriate time.
This also changes the “exception_raise” attribute to point to the method that will, in fact
- execute() None[source]#
Called to execute the task.
This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in prepare(), executed() or failed().
- executed() None[source]#
Called when the task has been successfully executed and the Taskmaster instance wants to call the Node’s callback methods.
This may have been a do-nothing operation (to preserve build order), so we must check the node’s state before deciding whether it was “built”, in which case we call the appropriate Node method. In any event, we always call “visited()”, which will handle any post-visit actions that must take place regardless of whether or not the target was an actual built target or a source Node.
- executed_with_callbacks() None#
Called when the task has been successfully executed and the Taskmaster instance wants to call the Node’s callback methods.
This may have been a do-nothing operation (to preserve build order), so we must check the node’s state before deciding whether it was “built”, in which case we call the appropriate Node method. In any event, we always call “visited()”, which will handle any post-visit actions that must take place regardless of whether or not the target was an actual built target or a source Node.
- executed_without_callbacks() None#
Called when the task has been successfully executed and the Taskmaster instance doesn’t want to call the Node’s callback methods.
- fail_continue() None#
Explicit continue-the-build failure.
This sets failure status on the target nodes and all of their dependent parent nodes.
Note: Although this function is normally invoked on nodes in the executing state, it might also be invoked on up-to-date nodes when using Configure().
- fail_stop() None#
Explicit stop-the-build failure.
This sets failure status on the target nodes and all of their dependent parent nodes.
Note: Although this function is normally invoked on nodes in the executing state, it might also be invoked on up-to-date nodes when using Configure().
- failed() None#
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() None#
Marks all targets in a task ready for execution.
This is used when the interface needs every target Node to be visited–the canonical example being the “scons -c” option.
- make_ready_current()#
Marks all targets in a task ready for execution if any target is not current.
This is the default behavior for building only what’s necessary.
- needs_execute() bool#
Always returns True (indicating this Task should always be executed).
Subclasses that need this behavior (as opposed to the default of only executing Nodes that are out of date w.r.t. their dependencies) can use this as follows:
- class MyTaskSubclass(SCons.Taskmaster.Task):
needs_execute = SCons.Taskmaster.AlwaysTask.needs_execute
- postprocess() None#
Post-processes a task after it’s been executed.
This examines all the targets just built (or not, we don’t care if the build was successful, or even if there was no build because everything was up-to-date) to see if they have any waiting parent Nodes, or Nodes waiting on a common side effect, that can be put back on the candidates list.
- prepare() None[source]#
Called just before the task is executed.
This is mainly intended to give the target Nodes a chance to unlink underlying files and make all necessary directories before the Action is actually called to build the targets.
- trace_message(node, description: str = 'node') None#
- exception SCons.Script.Main.SConsPrintHelpException[source]#
Bases:
Exception- add_note()#
Exception.add_note(note) – add a note to the exception
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- class SCons.Script.Main.TreePrinter(derived: bool = False, prune: bool = False, status: bool = False, sLineDraw: bool = False)[source]#
Bases:
object
- SCons.Script.Main.ValidateOptions(throw_exception: bool = False) None[source]#
Validate options passed to SCons on the command line.
Checks that all options given on the command line are known to this instance of SCons. Call after all of the cli options have been set up through
AddOption()calls. For example, if you added an option--xyzand you call SCons with--xyyyou can cause SCons to issue an error message and exit by calling this function.- Parameters:
throw_exception – if an invalid option is present on the command line, raises an exception if this optional parameter evaluates true; if false (the default), issue a message and exit with error status.
- Raises:
SConsBadOptionError – If throw_exception is true and there are invalid options on the command line.
Added in version 4.5.0.
- SCons.Script.Main._SConstruct_exists(dirname: str, repositories: list[str], filelist: list[str]) str | None[source]#
Check that an SConstruct file exists in a directory.
- Parameters:
dirname – the directory to search. If empty, look in cwd.
repositories – a list of repositories to search in addition to the project directory tree.
filelist – names of SConstruct file(s) to search for. If empty list, use the built-in list of names.
- Returns:
The path to the located SConstruct file, or
None.
- SCons.Script.Main._load_all_site_scons_dirs(topdir, verbose: bool = False) None[source]#
Load all of the predefined site_scons dir. Order is significant; we load them in order from most generic (machine-wide) to most specific (topdir). The verbose argument is only for testing.
- SCons.Script.Main._load_site_scons_dir(topdir, site_dir_name=None)[source]#
Load the site directory under topdir.
If a site dir name is supplied use it, else use default “site_scons” Prepend site dir to sys.path. If a “site_tools” subdir exists, prepend to toolpath. Import “site_init.py” from site dir if it exists.
- SCons.Script.Main._scons_internal_error() None[source]#
Handle all errors but user errors. Print out a message telling the user what to do in this case and print a normal trace.
- SCons.Script.Main._scons_internal_warning(e) None[source]#
Slightly different from _scons_user_warning in that we use the current call stack rather than sys.exc_info() to get our stack trace. This is used by the warnings framework to print warnings.
- SCons.Script.Main._scons_syntax_error(e) None[source]#
Handle syntax errors. Print out a message and show where the error occurred.
- SCons.Script.Main._scons_user_error(e) None[source]#
Handle user errors. Print out a message and a description of the error, along with the line number and routine where it occured. The file and line number will be the deepest stack frame that is not part of SCons itself.
- SCons.Script.Main._scons_user_warning(e) None[source]#
Handle user warnings. Print out a message and a description of the warning, along with the line number and routine where it occured. The file and line number will be the deepest stack frame that is not part of SCons itself.
SCons.Script.SConsOptions module#
- SCons.Script.SConsOptions.Parser(version)[source]#
Returns a parser object initialized with the standard SCons options.
Add options in the order we want them to show up in the
-Hhelp text, basically alphabetical. For readability, Eachadd_option()call should have a consistent format:op.add_option( "-L", "--long-option-name", nargs=1, type="string", dest="long_option_name", default='foo', action="callback", callback=opt_long_option, help="help text goes here", metavar="VAR" )
Even though the
optparsemodule constructs reasonable default destination names from the long option names, we’re going to be explicit about each one for easier readability and so this code will at least show up when grepping the source for option attribute names, or otherwise browsing the source code.
- exception SCons.Script.SConsOptions.SConsBadOptionError(opt_str: str, parser: SConsOptionParser | None = None)[source]#
Bases:
BadOptionErrorSCons handler for bad options.
- Variables:
opt_str – The unrecognized command-line option.
parser – The active argument parser.
- class SCons.Script.SConsOptions.SConsIndentedHelpFormatter(indent_increment=2, max_help_position=24, width=None, short_first=1)[source]#
Bases:
IndentedHelpFormatterSCons help formatting.
This is the SCons-specific
HelpFormatter()subclass, implemented by extendingoptparse.IndentedHelpFormatter().- format_heading(heading)[source]#
Translate heading to “SCons Options”
Heading of “Options” changed to “SCons Options.” Unfortunately, we have to intercept it here, because those titles are hard-coded in the optparse calls.
- format_option(option)[source]#
SCons-specific option formatter.
Vendors
optparse.HelpFormatter.format_option(), overridden to modify text wrapping to our liking:add our own regular expression that doesn’t break on hyphens (so things like
--no-print-directorydon’t get broken).wrap the list of options themselves when it’s too long (the
wrapper.fill(opts)call below).set the
subsequent_indentwhen wrapping thehelp_text.
The help for each option consists of two parts:
the opt strings and metavars e.g. (
-x, or-fFILENAME, --file=FILENAME)the user-supplied help string e.g. (
turn on expert mode,read data from FILENAME)
If possible, we write both of these on the same line:
-x turn on expert mode
If the opt string list is too long, we put the help string on a second line, indented to the same column it would start in if it fit on the first line:
-fFILENAME, --file=FILENAME read data from FILENAME
Help strings are wrapped for terminal width and do not preserve any hand-made formatting that may have been used in the
AddOption()call, so don’t attempt prettying up a list of choices (for example).
- class SCons.Script.SConsOptions.SConsOption(*opts, **attrs)[source]#
Bases:
OptionSCons added option.
Changes
CHECK_METHODSandCONST_ACTIONSsettings to tune for our usage.New function
_check_nargs_optional()implements thenargs=?syntax fromargparse, and is added to theCHECK_METHODSlist. Overriddenconvert_value()supports this usage.Changed in version 4.9.0: The settable attribute is added to
ATTRS, allowing it to be set in the option. A parameter to mark the option settable was added in 4.8.0, but was not initially made part of the option object itself.- ATTRS = ['action', 'type', 'dest', 'default', 'nargs', 'const', 'choices', 'callback', 'callback_args', 'callback_kwargs', 'help', 'metavar', 'settable']#
- CHECK_METHODS = [<function Option._check_action>, <function Option._check_type>, <function Option._check_choice>, <function Option._check_dest>, <function Option._check_const>, <function Option._check_nargs>, <function Option._check_callback>, <function SConsOption._check_nargs_optional>]#
- CONST_ACTIONS = ('store_const', 'append_const', 'store', 'append', 'callback')#
- class SCons.Script.SConsOptions.SConsOptionGroup(parser, title, description=None)[source]#
Bases:
OptionGroupSCons option groups.
The only difference between this and the base class is that we print the group’s help text flush left, underneath their own title but lined up with the normal “SCons Options”.
- class SCons.Script.SConsOptions.SConsOptionParser(usage=None, option_list=None, option_class=<class 'optparse.Option'>, version=None, conflict_handler='error', description=None, formatter=None, add_help_option=True, prog=None, epilog=None)[source]#
Bases:
OptionParserSCons option parser.
- _process_long_opt(rargs, values) None[source]#
SCons-specific processing of long options.
Vendors
_process_long_opt(). If configured to do so, catch the unknown option exception and stick the option back on the “leftover” arguments for later (re-)processing. This is because we may see the option definition later in the form of aAddOption()while reading SConscript files.
- _process_short_opts(rargs, values) None[source]#
SCons-specific processing of short options.
Vendors
_process_short_opts(). If configured to do so, catch the unknown option exception and stick the option back on the “leftover” arguments for later (re-)processing. This is because we may see the option definition later in the form of aAddOption()while reading SConscript files.
- add_local_option(*args, **kw) SConsOption[source]#
Add a local option to the parser.
This is the implementation of
AddOption(), to add a project-defined command-line option. Local options are added to a separate option group, which is created if necessary.The keyword argument settable is recognized specially (and removed from kw). If true, the option is marked as modifiable; by default “local” (project-added) options are not eligible for
SetOption()calls.Changed in version 4.9.0: If the option’s settable attribute is true, it is added to the
SConsValues.settablelist. settable handling was added in 4.8.0, but was not made an option attribute at the time.
- format_local_option_help(formatter=None, file=None)[source]#
Return the help for the project-level (“local”) SCons options.
Added in version 4.6.0.
- preserve_unknown_options = False#
- print_local_option_help(file=None)[source]#
Print help for just local SCons options.
Writes to file (default stdout).
Added in version 4.6.0.
- raise_exception_on_error = False#
- class SCons.Script.SConsOptions.SConsValues(defaults)[source]#
Bases:
ValuesSCons parsed argument names and values.
A SCons option value can originate three different ways:
set on the command line.
set in an SConscript file via
SetOption().the default setting (from the the
op.add_option()calls in theParser()function.
The command line always overrides a value set in a SConscript file, which in turn always overrides default settings. Because we want to support user-specified options in the SConscript file itself, though, we may not know about all of the options when the command line is first parsed, so we can’t make all the necessary precedence decisions at the time the option is configured.
The solution implemented in this class is to keep these different sets of settings separate (command line, SConscript file, and default) and to override the
__getattr__()method to check them in turn. This allows the rest of the code to just fetch values as attributes of an instance of this class, without having to worry about where they came from (the scheme is similar to aChainMap).Note that not all command line options are settable from SConscript files, and the ones that are must be explicitly added to the
settablelist in this class, and optionally validated and coerced in theset_option()method.- __getattr__(attr)[source]#
Fetch an options value, respecting priority rules.
This is a little tricky: since we’re answering questions about outselves, we have avoid lookups that would send us into into infinite recursion, thus the
__dict__stuff.
- set_option(name: str, value) None[source]#
Set an option value from a
SetOption()call.Validation steps for settable options (those defined in SCons itself) are in-line here. Duplicates the logic for the matching command-line options in
Parse()- these need to be kept in sync. Cannot provide validation for options added viaAddOption()since we don’t know about those ahead of time - it is up to the developer to figure that out.- Raises:
UserError – the option is not settable.
- settable = ['clean', 'diskcheck', 'duplicate', 'experimental', 'hash_chunksize', 'hash_format', 'help', 'implicit_cache', 'implicit_deps_changed', 'implicit_deps_unchanged', 'max_drift', 'md5_chunksize', 'no_exec', 'no_progress', 'num_jobs', 'random', 'silent', 'stack_size', 'warn']#
SCons.Script.SConscript module#
This module defines the Python API provided to SConscript files.
- SCons.Script.SConscript.BuildDefaultGlobals()[source]#
Create a dictionary containing all the default globals for SConstruct and SConscript files.
- class SCons.Script.SConscript.DefaultEnvironmentCall(method_name, subst: int = 0)[source]#
Bases:
objectA class that implements “global function” calls of Environment methods by fetching the specified method from the DefaultEnvironment’s class. Note that this uses an intermediate proxy class instead of calling the DefaultEnvironment method directly so that the proxy can override the subst() method and thereby prevent expansion of construction variables (since from the user’s point of view this was called as a global function, with no associated construction environment).
- class SCons.Script.SConscript.Frame(fs: FS, exports, sconscript: str | Node)[source]#
Bases:
objectA frame on the SConstruct/SConscript call stack
- class SCons.Script.SConscript.SConsEnvironment(platform: str | PlatformSpec | None = None, tools: list[str | tuple[str, dict[str, Any]]] | None = None, toolpath: list[str] | None = None, variables: Variables | None = None, parse_flags: str | list[str] | dict[str, Any] | None = None, **kw)[source]#
Bases:
BaseAn Environment subclass that contains all of the methods that are particular to the wrapper SCons interface and which aren’t (or shouldn’t be) part of the build engine itself.
Note that not all of the methods of this class have corresponding global functions, there are some private methods.
- Action(*args, **kw) ActionBase#
Create and return an Action object.
- AddMethod(function: Callable[[...], Any | None], name: str | None = None) None#
Add function as method
env.function.Creates a
MethodWrapperinstance and adds it to theadded_methodslist.If name is omitted, the name of the function itself is used.
- AddPostAction(files: str | Node | list[str | Node], action) list[Node]#
Set an action to be performed after files are built.
- Returns:
a list of the affected Nodes.
- AddPreAction(files: str | Node | list[str | Node], action) list[Node]#
Set an action to be performed before files are built.
- Returns:
a list of the affected Nodes.
- Alias(target: str | Node | list[str | Node], source: str | Node | list[str | Node] | None = None, action=None, **kw) list[Node]#
Create an alias target that depends on source.
- Append(**kw) None#
Append values to construction variables in an Environment.
The variable is created if it is not already present.
- AppendENVPath(name: str, newpath: str | list[str], envname: str = 'ENV', sep: str = ':', delete_existing: bool = False) None#
Append path elements to the path variable name in envname.
This is a convenience function for the case where the subject path variable is “down a level”, as in
env['ENV']['PATH']. The hard work is done byAppendPath().- Parameters:
name – the path variable to add paths to
newpath – the new paths to add
envname – the name of the environment dictionary to update
sep – the pathname separator to use. Defaults to the system’s native path separator.
delete_existing – if false, any newpath component already in the path will not be moved to the end, but left where it is. Default is
True.
- AppendUnique(delete_existing: bool = False, **kw) None#
Append values uniquely to existing construction variables.
Similar to
Append(), but the result may not contain duplicates of any values passed for each given key (construction variable), so an existing list may need to be pruned first, however it may still contain other duplicates.If delete_existing is true, removes existing values first, so values move to the end; otherwise (the default) values are skipped if already present.
- Builder(**kw)#
Create and return a Builder object.
- CacheDir(path: str | None, custom_class: type | None = None) None#
Set up a CacheDir for this environment.
- Parameters:
path – Path to the CacheDir directory. If
None, disables caching.custom_class – Optional custom CacheDir class to use.
- Clean(targets: str | Node | list[str | Node], files: str | Node | list[str | Node]) None#
Mark additional files for cleaning.
files will be removed if any of targets are selected, and clean mode is active.
- Clone(tools: list[str | tuple[str, dict[str, Any]]] = [], toolpath: list[str] | None = None, variables: Variables | None = None, parse_flags: str | list[str] | dict[str, Any] | None = None, **kw)#
Return a copy of a construction Environment.
The copy is like a Python “deep copy”: independent copies are made recursively of each object, 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.
Unrecognized keyword arguments are taken as construction variable assignments.
- Parameters:
tools – name or list of tool names to initialize.
toolpath – list of paths to search for tools.
variables – a
Variablesobject to use to populate construction variables from command-line variables.parse_flags – option strings to parse into construction variables.
Changed in version 4.8.0: The optional variables parameter was added.
- Command(target, source, action, **kw) list[Node]#
Set up a one-off build command.
Builds target from source using action, which may be be any type that the Builder factory will accept for an action. Generates an anonymous builder and calls it, to add the details to the build graph. The builder is not named, added to
BUILDERS, or otherwise saved.Recognizes the
Builder()keywordssource_scanner,target_scanner,source_factoryandtarget_factory. All other arguments from kw are passed on to the builder when it is called.
- Decider(function: str | Callable[[FileNode, FileNode, NodeInfoBase, Node | None], bool]) None#
Set the decision function for whether targets need rebuilding.
- Depends(target: str | Node | list[str | Node], dependency: str | Node | list[str | Node]) list[Node]#
Explicity specify that target depends on dependency.
- Detect(progs: str | list[str]) str | None#
Return the first available program from one or more possibilities.
- Parameters:
progs – one or more command names to check for availability.
- Dictionary(*args: str, as_dict: bool = False) Any | list[Any] | dict[str, Any]#
Return construction variables from an environment.
- Parameters:
args (optional) – construction variable names to select. If omitted, all variables are selected and returned as a dict.
as_dict – if true, and args is supplied, return the variables and their values in a dict. If false (the default), return a single value as a scalar, or multiple values in a list.
- Returns:
A dictionary of construction variables, or a single value or list of values.
- Raises:
KeyError – if any of args is not in the construction environment.
Changed in version 4.9.0: Added the as_dict keyword arg to specify always returning a dict.
- Dir(name: str | Node | list[str | Node], *args, **kw) DirNode | list[DirNode]#
Create Dir node(s) for name.
- Dump(*key: str, format: str = 'pretty') str#
Return string of serialized construction variables.
Produces a “pretty” output of a dictionary of selected construction variables, or all of them. The display format is selectable. The result is intended for human consumption (e.g, to print), mainly when debugging. Objects that cannot directly be represented get a placeholder like
<function foo at 0x123456>(pretty-print) or<<non-serializable: function>>(JSON).- Parameters:
key – variables to format together with their values. If omitted, format the whole dict of variables,
format – specify the format to serialize to.
"pretty"generates a pretty-printed string,"json"a JSON-formatted string.
- Raises:
ValueError – format is not a recognized serialization format.
Changed in version 4.9.0: key is no longer limited to a single construction variable name. If key is supplied, a formatted dictionary is generated like the no-arg case - previously a single key displayed just the value.
- static EnsurePythonVersion(major: int, minor: int) None[source]#
Exit abnormally if the Python version is not late enough.
- static EnsureSConsVersion(major: int, minor: int, revision: int = 0) None[source]#
Exit abnormally if the SCons version is not late enough.
- Entry(name: str | Node | list[str | Node], *args, **kw) EntryNode | list[EntryNode]#
Create Entry node(s) for name.
- Execute(action, *args, **kw)#
Directly execute action through an Environment.
- File(name: str | Node | list[str | Node], *args, **kw) FileNode | list[FileNode]#
Create File node(s) for name.
- FindFile(file: str, dirs: str | Node | list[str | Node]) FileNode | None#
Find file in dirs and return the corresponding Node.
- static FindInstalledFiles() list[FileNode]#
Return the list of all targets of the Install and InstallAs Builders.
- FindIxes(paths: list[str], prefix: str, suffix: str) str | None#
Search paths for a path that has prefix and suffix.
Returns on first match.
- Parameters:
paths – the list of paths or nodes.
prefix – construction variable for the prefix.
suffix – construction variable for the suffix.
- Returns:
The matched path or
None
- FindSourceFiles(node: str | Node = '.') list[EntryNode]#
Return the list of all source files under node.
- static Flatten(sequence: Any) list#
Flatten a nested sequence into a single list.
sequence can also be a scalar, which still returns a list. See
SCons.Util.flatten().
- static GetSConsVersion() tuple[int, int, int][source]#
Return the current SCons version.
Added in version 4.8.0.
- Glob(pattern: str, ondisk: bool = True, source: bool = False, strings: bool = False, exclude: str | list[str] | None = None) list[Node] | list[str]#
Return a list of nodes matching pattern.
- Help(text: str, append: bool = False, local_only: bool = False) None[source]#
Update the help text.
The previous help text has text appended to it, except on the first call. On first call, the values of append and local_only are considered to determine what is appended to.
- Parameters:
text – string to add to the help text.
append – on first call, if true, keep the existing help text (default False).
local_only – on first call, if true and append is also true, keep only the help text from AddOption calls.
Changed in version 4.6.0: The keep_local parameter was added.
Changed in version 4.9.0: The keep_local parameter was renamed local_only to match manpage
- Ignore(target: str | Node | list[str | Node], dependency: str | Node | list[str | Node]) list[Node]#
Ignore dependency for target.
- Local(*targets: str | Node | list[str | Node]) list[Node]#
Mark targets as local: do not look in repositories.
- MergeFlags(args: str | list[str] | dict[str, Any], unique: bool = True) None#
Merge flags into construction variables.
Merges the flags from args into this construction environent. If args is not a dict, it is first converted to one with flags distributed into appropriate construction variables. See
ParseFlags().As a side effect, if unique is true, a new object is created for each modified construction variable by the loop at the end. This is silently expected by the
Override()parse_flags functionality, which does not want to share the list (or whatever) with the environment being overridden.- Parameters:
args – flags to merge
unique – merge flags rather than appending (default: True). When merging, path variables are retained from the front, other construction variables from the end.
- NoClean(*targets: str | Node | list[str | Node]) list[Node]#
Tag targets to not be removed in clean mode.
- Override(overrides: dict[str, Any]) Base#
Create an override environment.
Produces a modified environment where the current variables are overridden by any same-named variables from the overrides dict.
An override is much more efficient than doing
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.Using this method is preferred over directly instantiating an
OverrideEnvirionmentbecause extra checks are performed, substitution takes place, and there is special handling for a parse_flags keyword argument.This method is not currently exposed as part of the public API, but is invoked internally when things like builder calls have keyword arguments, which are then passed as overrides here. Some tools also call this explicitly.
- Returns:
A proxy environment of type
OverrideEnvironment. or the current environment if overrides is empty.
- ParseConfig(command, function=None, unique: bool = True) Any | None#
Parse the result of running a command to update construction vars.
Call function to parse the output of running command in order to modify the current construction environment.
- Parameters:
command – a string or a list of strings representing a command and its arguments.
function – called to process the result of command, which will be passed as the args argument. If function is omitted or
None,MergeFlags()is used. Takes 3 args(env, args, unique)unique – if true (the default) no duplicate values are allowed
- ParseDepends(filename: str, must_exist: bool = False, only_one: bool = False) None#
Parse a depends-style file filename 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. It can also be genuinely useful when using a tool that can write a
.dfile, but for which writing a scanner would be too complicated.
- ParseFlags(*flags: str | list[str]) dict[str, Any]#
Parse flags into a dict of construction variables.
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 emitted by
pkg-configfor a specific package (or a standalonesomething-config), 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: str) PlatformSpec#
Call a platform object to update the environment.
- Precious(*targets: str | Node | list[str | Node]) list[Node]#
Mark targets as precious: do not delete before building.
- Prepend(**kw) None#
Prepend values to construction variables.
The variable is created if it is not already present.
- PrependENVPath(name: str, newpath: str | list[str], envname: str = 'ENV', sep: str = ':', delete_existing: bool = True) None#
Prepend path elements to the path variable name in envname.
This is a convenience function for the case where the subject path variable is “down a level”, as in
env['ENV']['PATH']. The hard work is done byPrependPath().- Parameters:
name – the path variable to add paths to
newpath – the new paths to add
envname – the name of the environment dictionary to update
sep – the pathname separator to use. Defaults to the system’s native path separator.
delete_existing – if false, any newpath component already in the path will not be moved to the front, but left where it is. Default is
True.
- PrependUnique(delete_existing: bool = False, **kw) None#
Prepend values uniquely to existing construction variables.
Similar to
Prepend(), but the result may not contain duplicates of any values passed for each given key (construction variable), so an existing list may need to be pruned first, however it may still contain other duplicates.If delete_existing is true, removes existing values first, so values move to the front; otherwise (the default) values are skipped if already present.
- PyPackageDir(modulename: str | Node | list[str | Node]) DirNode | list[DirNode | None] | None#
Create Dir node(s) for modulename.
- RemoveMethod(function: Callable[[...], Any | None]) None#
Remove function as a method.
Removes the specified function’s
MethodWrapperfrom theadded_methodslist, so we don’t re-bind it when making a clone.
- Replace(**kw) None#
Assign new values to construction variables.
If a variable does not exist in the environment, it is added. See also
SetDefault().
- ReplaceIxes(path: str, old_prefix: str, old_suffix: str, new_prefix: str, new_suffix: str) str#
Replace prefixes and/or suffixes in a path.
- Parameters:
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: str | DirNode | list[str | DirNode]) None#
Specify Repository directories to search.
- Requires(target: str | Node | list[str | Node], prerequisite: str | Node | list[str | Node]) list[Node]#
Specify that prerequisite must be built before target.
Creates an order-only relationship, not a full dependency. prerequisite must exist before target can be built, but a change to prerequisite does not trigger a rebuild of target.
- SConscript(*ls: str | Node | list[str | Node], **kw)[source]#
Execute SCons configuration files.
- Parameters:
*ls (str or list) – configuration file(s) to execute.
- Keyword Arguments:
dirs (list) – execute SConscript in each listed directory.
name (str) – execute script ‘name’ (used only with ‘dirs’).
exports (list or dict) – locally export variables the called script(s) can import.
variant_dir (str) – mirror sources needed for the build in a variant directory to allow building in it.
duplicate (bool) – physically duplicate sources instead of just adjusting paths of derived files (used only with ‘variant_dir’) (default is True).
must_exist (bool) – fail if a requested script is missing (default is False, default is deprecated).
- Returns:
list of variables returned by the called script
- Raises:
UserError – a script is not found and such exceptions are enabled.
- SConsignFile(name: str | None = '', dbm_module: ModuleType | None = None) None#
Specify the base name of the signature database.
If name is not specified,
.sconsignis used as the base name. The actual name may also include an indicator of the hash algorithm used to calculate the signatures, and a suffix indicating the storage format. If the hash algorithm is set viaSetOption(), that setting must occur before this function is called.If dbm_module is specified, it gives the database module to use. The parameter must be an actual module object, not a string name. The module must follow the Python Database API specification described in PEP 249. The defaut is
SCons.dblite.For historical reasons, if name is
None, the signatures are stored as one file per directory, rather than in a single project-wide database.Deprecated since version 4.11.0: The signature-file-per-directory mode is deprecated.
- Scanner(*args, **kw) ScannerBase#
Create a Scanner object.
A thin wrapper around the class initializer; performs environment-specific substitution on the arguments before handing off.
- SetDefault(**kw) None#
Set construction variables if they do not already have values.
If a variable already exists in the environment, it is unchanged. See also
Replace().
- SideEffect(side_effect: str | Node | list[str | Node], target: str | Node | list[str | Node]) list[Node]#
Record that side_effects are also built when building target.
- Split(arg: str | Node | list[str] | list[Node] | list[str | Node]) list[str] | list[Node] | list[str | Node]#
Convert arg into a list of strings or Nodes.
If arg is a string, it is split on whitespace. This makes things easier for users by allowing files to be specified as a white-space separated list to be split without having to use lots of quotes and commas. Otherwise, things are pretty much unchanged, allowing
Splitto be safely called in various circumstances without checking types. The input rules are:A single string containing names separated by spaces. These will be split apart at the spaces.
A single Node instance. Unchanged.
A list containing either strings or Node instances. String-valueed elements are not split at spaces. Nodes are unchanged.
- Tool(tool: str | Callable, toolpath: Collection[str] | None = None, **kwargs) Tool#
Find and run tool module tool.
tool is generally a string, but can also be a callable object, in which case it is just called, without any of the setup. The setup stores kwargs into the created
Toolinstance, which is extracted and used when the instance is called, so in the skip case, the called object will not see the kwargs.Changed in version 4.2: returns the tool object rather than
None.
- Value(value: Any | None, built_value: Any | None = None, name: str | None = None) Value#
Return a value Node ((Python expression).
Changed in version 4.0: the name parameter was added.
- VariantDir(variant_dir: str | Node, src_dir: str | Node, duplicate: bool = True) None#
Create a VariantDir mapping.
This function creates a mapping from the source directory src_dir to the variant directory variant_dir. If duplicate is true (the default), the source files are duplicated into the variant directory; otherwise they are not.
- WhereIs(prog: str, path: str | list[str] | None = None, pathext: str | list[str] | None = None, reject: list[str] | None = None) str | None#
Find an executable program in the search path.
Each path is searched for prog (after substitution). If path is
None, the execution environment path (['ENV']['PATH']) is used, unless that is unset - then use the external environment’s search path (os.environ['PATH']) Any names/paths in reject are ignored.On Windows, each extension in pathext is sequentially tried when checking for prog If pathext is
None, the value from the execution environment (['ENV']['PATHEXT']) is used, unless that is unset - then use the value from the external environment (os.environ['PATHEXT']).This is a wrapper for
SCons.Util.WhereIs()which enforces some of the rules and performs the actual search.- Parameters:
prog – program to search for
path – specific paths to search. Defaults to
None.pathext – filename extensions to search. Defaults to
None.reject – names to exclude from match. Defaults to
None.
- Returns:
The full path to the program if found, or
None.
- __eq__(other) bool#
Compare two environments.
This is used by checks in Builder to determine if duplicate targets have environments that would cause the same result. The more reliable way (respecting the admonition to avoid poking at
_dictdirectly) would be to useDictionaryso this is sure to work even if one or both are are instances ofOverrideEnvironment. However an actualSubstitutionEnvironmentdoesn’t have aDictionarymethod That causes problems for unit tests written to exerciseSubsitutionEnvironmentdirectly, although nobody else seems to ever instantiate one. We count onOverrideEnvironmentto fake the_dictto make things work.
- __getattr__(name: str) NoReturn#
Handle missing attribute in an environment.
Assume this is a builder that’s not instantiated, becasue that has been a common failure mode. Could also be a typo. Emit a message about this to try to help. We can’t get too clever, other parts of SCons depend on seeing the
AttributeErrorthat triggers this call, so all we do is produce our own message.Added in version 4.10.0.
- _canonicalize(path) str#
Allow Dirs and strings beginning with # for top-relative.
Note this uses the current env’s fs (in self).
- _changed_build(dependency: FileNode, target: FileNode, prev_ni: NodeInfoBase, repo_node: Node | None = None) bool#
Decide whether a target needs to be rebuilt based on a dependency.
- static _changed_content(dependency: FileNode, target: FileNode, prev_ni: NodeInfoBase, repo_node: Node | None = None) bool#
Decide whether a target needs to be rebuilt based on content change.
- static _changed_timestamp_match(dependency: FileNode, target: FileNode, prev_ni: NodeInfoBase, repo_node: Node | None = None) bool#
Decide whether a target needs to be rebuilt based on timestamp matching.
- static _changed_timestamp_newer(dependency: FileNode, target: FileNode, prev_ni: NodeInfoBase, repo_node: Node | None = None) bool#
Decide whether a target needs to be rebuilt based on newer timestamp.
- static _changed_timestamp_then_content(dependency: FileNode, target: FileNode, prev_ni: NodeInfoBase, repo_node: Node | None = None) bool#
Decide whether a target needs to be rebuilt based on timestamp then content.
- _dict: dict[str, Any]#
- _find_toolpath_dir(tp)#
Helper to find a toolpath directory.
- _get_SConscript_filenames(ls, kw) tuple[list[str], list[str | Node]][source]#
Convert the parameters passed to SConscript() calls into a list of files and export variables. If the parameters are invalid, throws SCons.Errors.UserError. Returns a tuple (l, e) where l is a list of SConscript filenames and e is a list of exports.
- static _get_major_minor_revision(version_string: str) tuple[int, int, int][source]#
Split a version string into major, minor and (optionally) revision parts.
This is complicated by the fact that a version string can be something like 3.2b1.
- _gsm()#
- _init_special() None#
Initialize the dispatch tables for special construction variables.
- _memo: dict[str, Any]#
- _update(other: dict[str, Any]) None#
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: dict[str, Any]) None#
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 setting items through the public API.
- added_methods: list[MethodWrapper]#
- arg2nodes(args: str | Node | list[str | Node], node_factory: Callable[[str], Node | list[Node]] | None = <SCons.Util.sctypes._Null object>, lookup_list: list[Callable[[str], Node | None]] = <SCons.Util.sctypes._Null object>, **kw) list[Node]#
Convert args to a list of nodes.
- Parameters:
args – sequence of filename strings or nodes to convert. Nodes are added to the list without further processing.
node_factory – optional factory to create the nodes; if not specified, will use this environment’s
fs.Filemethod.lookup_list – optional list of lookup functions to call to attempt to find each file referenced by args.
kw – keyword arguments that represent additional nodes to add.
- Returns:
a list of nodes.
- backtick(command: str | list[str]) 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: str, default: Any | None = None) Any#
Emulate the
getmethod of dictionaries.
- get_CacheDir() CacheDir#
Return the CacheDir object for this environment, instantiating it if necessary.
- get_builder(name: str) BuilderBase | None#
Fetch the builder with the specified name from the environment.
- get_factory(factory, default: str = 'File')#
Return a factory function for creating Nodes.
- get_scanner(skey: str) ScannerBase | None#
Find the appropriate scanner given a key (usually a file suffix).
- gvars() dict[str, Any]#
Return the global construction variables dictionary.
- items()#
Emulate the
itemsmethod of dictionaries.
- keys()#
Emulate the
keysmethod of dictionaries.
- lvars() dict[str, Any]#
Return the local construction variables dictionary.
- scanner_map_delete(kw=None) None#
Delete the cached scanner map (if necessary).
- setdefault(key: str, default: Any | None = None) Any | None#
Emulate the
setdefaultmethod of dictionaries.
- subst(string: str | list[str], raw: int = 0, target: Any | None = None, source: Any | None = None, conv: Callable[[Any], str] | None = None, executor: Executor | None = None, overrides: dict[str, Any] | None = None) str | list[str]#
Substitute construction variables (recursively) into string.
This is the Public entry point for substitution, despite not using the CapWords convention SCons usually follows for such interfaces. The related methods
subst_kw(),subst_list()andsubst_path()are not exported as part of the Public API.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.The hard work is done by
SCons.Subst.scons_subst().
- subst_kw(kw: dict[str, Any], raw: int = 0, target: Any | None = None, source: Any | None = None) dict[str, Any]#
Substitute all keys and string values in a keyword dictionary.
- subst_list(string: str, raw: int = 0, target: Any | None = None, source: Any | None = None, conv: Callable[[Any], str] | None = None, executor: Executor | None = None, overrides: dict[str, Any] | None = None) list[str]#
Perform substitution and produce a command list.
The hard work is done by
SCons.Subst.scons_subst_list().
- subst_path(path: str | list[str], target: Any | None = None, source: Any | None = None) list[str]#
Perform substitution on a path list.
Turns each
EntryProxyinto a Node, leaving Nodes (and other objects) as-is.
- subst_target_source(string: str | list[str], raw: int = 0, target: Any | None = None, source: Any | None = None, conv: Callable[[Any], str] | None = None, executor: Executor | None = None, overrides: dict[str, Any] | None = None) str | list[str]#
Substitute construction variables (recursively) into string.
This is the Public entry point for substitution, despite not using the CapWords convention SCons usually follows for such interfaces. The related methods
subst_kw(),subst_list()andsubst_path()are not exported as part of the Public API.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.The hard work is done by
SCons.Subst.scons_subst().
- validate_CacheDir_class(custom_class: type | None = None) type#
Return a validated custom CacheDir class.
Validate that custom_class, is derived from
SCons.CacheDir.CacheDir. If custom_class is not supplied, use theCACHEDIR_CLASSentry from the environment. Return the class if there was no error.- Raises:
UserError – if the class is not derived from
CacheDir.
- values()#
Emulate the
valuesmethod of dictionaries.
- exception SCons.Script.SConscript.SConscriptReturn[source]#
Bases:
Exception- add_note()#
Exception.add_note(note) – add a note to the exception
- args#
- with_traceback()#
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- SCons.Script.SConscript.SConscript_exception(file: TextIO = <_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>) None[source]#
Print an exception stack trace just for the SConscript file(s). This will show users who have Python errors where the problem is, without cluttering the output with all of the internal calls leading up to where we exec the SConscript.
- SCons.Script.SConscript.annotate(node: Node) None[source]#
Annotate a node with the stack frame describing the SConscript file and line number that created it.
- SCons.Script.SConscript.compute_exports(exports)[source]#
Compute a dictionary of exports given one of the parameters to the Export() function or the exports argument to SConscript().
- SCons.Script.SConscript.get_calling_namespaces()[source]#
Return the locals and globals for the function that called into this module in the current call stack.
- SCons.Script.SConscript.handle_missing_SConscript(f: File, must_exist: bool = True) None[source]#
Take appropriate action on missing file in SConscript() call.
Print a warning or raise an exception on missing file, unless missing is explicitly allowed by the must_exist parameter or by a global flag.
- Parameters:
f – path to missing configuration file
must_exist – if true (the default), fail. If false do nothing, allowing a build to declare it’s okay to be missing.
- Raises:
UserError – if must_exist is true or if global
SCons.Script._no_missing_sconscriptis true.