SCons.Script package

Submodules

SCons.Script.Interactive module

SCons interactive mode

class SCons.Script.Interactive.SConsInteractiveCmd(**kw)[source]

Bases: cmd.Cmd

build [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.

_do_one_help(arg)[source]
_doc_to_help(obj)[source]
_strip_initial_spaces(s)[source]
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)[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_EOF(argv)[source]
do_build(argv)[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_exit(argv)[source]

exit Exit SCons interactive mode.

do_help(argv)[source]

help [COMMAND] Prints help for the specified COMMAND. ‘h’ and ‘?’ are synonyms.

do_shell(argv)[source]

shell [COMMANDLINE] Execute COMMANDLINE in a subshell. ‘sh’ and ‘!’ are synonyms.

do_version(argv)[source]

version Prints SCons version information.

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.Interactive.interact(fs, parser, options, targets, target_top)[source]

SCons.Script.Main module

SCons.Script

This file implements 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)[source]
class SCons.Script.Main.BuildTask(tm, targets, top, node)[source]

Bases: SCons.Taskmaster.OutOfDateTask

An SCons build task.

_abc_impl = <_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.

do_failed(status=2)[source]
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()[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()

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()[source]

Make a task ready for execution

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()

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()[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()[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.

trace_message(method, node, description='node')
class SCons.Script.Main.CleanTask(tm, targets, top, node)[source]

Bases: SCons.Taskmaster.AlwaysTask

An SCons clean task.

_abc_impl = <_abc_data object>
_clean_targets(remove=True)[source]
_exception_raise()

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

_get_files_to_clean()[source]
_no_exception_to_raise()
display(message)

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()

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()
executed()

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()

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()

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().

fs_delete(path, pathstr, remove=True)[source]
get_target()

Fetch the target being built or updated by this task.

make_ready()

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()

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()

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()

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.

remove()[source]
show()[source]
trace_message(method, node, description='node')
class SCons.Script.Main.CountStats[source]

Bases: SCons.Script.Main.Stats

do_append(label)[source]
do_nothing(*args, **kw)
do_print()[source]
enable(outfp)
class SCons.Script.Main.FakeOptionParser[source]

Bases: object

A do-nothing option parser, used for the initial OptionsParser variable.

During normal SCons operation, the OptionsParser is created right away by the main() function. Certain tests 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.

class FakeOptionValues[source]

Bases: object

add_local_option(*args, **kw)[source]
values = <SCons.Script.Main.FakeOptionParser.FakeOptionValues object>
SCons.Script.Main.GetBuildFailures()[source]
SCons.Script.Main.GetOption(name)[source]
class SCons.Script.Main.MemStats[source]

Bases: SCons.Script.Main.Stats

do_append(label)[source]
do_nothing(*args, **kw)
do_print()[source]
enable(outfp)
SCons.Script.Main.PrintHelp(file=None)[source]
SCons.Script.Main.Progress(*args, **kw)[source]
class SCons.Script.Main.Progressor(obj, interval=1, file=None, overwrite=False)[source]

Bases: object

count = 0
erase_previous()[source]
prev = ''
replace_string(node)[source]
spinner(node)[source]
string(node)[source]
target_string = '$TARGET'
write(s)[source]
class SCons.Script.Main.QuestionTask(tm, targets, top, node)[source]

Bases: SCons.Taskmaster.AlwaysTask

An SCons task for the -q (question) option.

_abc_impl = <_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)

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()

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()[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()

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()

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()

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

postprocess()

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.

trace_message(method, node, description='node')
exception SCons.Script.Main.SConsPrintHelpException[source]

Bases: Exception

args
with_traceback()

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

SCons.Script.Main.SetOption(name, value)[source]
class SCons.Script.Main.Stats[source]

Bases: object

do_nothing(*args, **kw)[source]
enable(outfp)[source]
class SCons.Script.Main.TreePrinter(derived=False, prune=False, status=False, sLineDraw=False)[source]

Bases: object

display(t)[source]
get_all_children(node)[source]
get_derived_children(node)[source]
SCons.Script.Main._SConstruct_exists(dirname='', repositories=[], filelist=None)[source]

This function checks that an SConstruct file exists in a directory. If so, it returns the path of the file. By default, it checks the current directory.

SCons.Script.Main._build_targets(fs, options, targets, target_top)[source]
SCons.Script.Main._create_path(plist)[source]
SCons.Script.Main._exec_main(parser, values)[source]
SCons.Script.Main._load_all_site_scons_dirs(topdir, verbose=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._main(parser)[source]
SCons.Script.Main._scons_internal_error()[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)[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)[source]

Handle syntax errors. Print out a message and show where the error occurred.

SCons.Script.Main._scons_user_error(e)[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)[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.Main._set_debug_values(options)[source]
SCons.Script.Main.fetch_win32_parallel_msg()[source]
SCons.Script.Main.find_deepest_user_frame(tb)[source]

Find the deepest stack frame that is not part of SCons.

Input is a “pre-processed” stack trace in the form returned by traceback.extract_tb() or traceback.extract_stack()

SCons.Script.Main.main()[source]
SCons.Script.Main.path_string(label, module)[source]
SCons.Script.Main.python_version_deprecated(version=sys.version_info(major=3, minor=7, micro=8, releaselevel='final', serial=0))[source]
SCons.Script.Main.python_version_string()[source]
SCons.Script.Main.python_version_unsupported(version=sys.version_info(major=3, minor=7, micro=8, releaselevel='final', serial=0))[source]
SCons.Script.Main.revert_io()[source]
SCons.Script.Main.test_load_all_site_scons_dirs(d)[source]
SCons.Script.Main.version_string(label, module)[source]

SCons.Script.SConsOptions module

SCons.Script.SConsOptions.Parser(version)[source]

Returns an options parser object initialized with the standard SCons options.

class SCons.Script.SConsOptions.SConsIndentedHelpFormatter(indent_increment=2, max_help_position=24, width=None, short_first=1)[source]

Bases: optparse.IndentedHelpFormatter

NO_DEFAULT_VALUE = 'none'
_format_text(text)

Format a paragraph of free-form text for inclusion in the help output at the current indentation level.

dedent()
expand_default(option)
format_description(description)
format_epilog(epilog)
format_heading(heading)[source]

This translates any heading of “options” or “Options” into “SCons Options.” Unfortunately, we have to do this here, because those titles are hard-coded in the optparse calls.

format_option(option)[source]

A copy of the normal optparse.IndentedHelpFormatter.format_option() method. This has been snarfed so we can modify text wrapping to out liking:

– add our own regular expression that doesn’t break on hyphens

(so things like –no-print-directory don’t get broken);

– wrap the list of options themselves when it’s too long

(the wrapper.fill(opts) call below);

– set the subsequent_indent when wrapping the help_text.

format_option_strings(option)

Return a comma-separated list of option strings & metavariables.

format_usage(usage)[source]
indent()
set_long_opt_delimiter(delim)
set_parser(parser)
set_short_opt_delimiter(delim)
store_option_strings(parser)
class SCons.Script.SConsOptions.SConsOption(*opts, **attrs)[source]

Bases: optparse.Option

ACTIONS = ('store', 'store_const', 'store_true', 'store_false', 'append', 'append_const', 'count', 'callback', 'help', 'version')
ALWAYS_TYPED_ACTIONS = ('store', 'append')
ATTRS = ['action', 'type', 'dest', 'default', 'nargs', 'const', 'choices', 'callback', 'callback_args', 'callback_kwargs', 'help', 'metavar']
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')
STORE_ACTIONS = ('store', 'store_const', 'store_true', 'store_false', 'append', 'append_const', 'count')
TYPED_ACTIONS = ('store', 'append', 'callback')
TYPES = ('string', 'int', 'long', 'float', 'complex', 'choice')
TYPE_CHECKER = {'choice': <function check_choice>, 'complex': <function check_builtin>, 'float': <function check_builtin>, 'int': <function check_builtin>, 'long': <function check_builtin>}
_check_action()
_check_callback()
_check_choice()
_check_const()
_check_dest()
_check_nargs()
_check_nargs_optional()[source]
_check_opt_strings(opts)
_check_type()
_set_attrs(attrs)
_set_opt_strings(opts)
check_value(opt, value)
convert_value(opt, value)[source]
get_opt_string()
process(opt, value, values, parser)[source]
take_action(action, dest, opt, value, values, parser)
takes_value()
class SCons.Script.SConsOptions.SConsOptionGroup(parser, title, description=None)[source]

Bases: optparse.OptionGroup

A subclass for SCons-specific 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”.

_check_conflict(option)
_create_option_list()
_create_option_mappings()
_share_option_mappings(parser)
add_option(Option)

add_option(opt_str, …, kwarg=val, …)

add_options(option_list)
destroy()

see OptionParser.destroy().

format_description(formatter)
format_help(formatter)[source]

Format an option group’s help text, outdenting the title so it’s flush with the “SCons Options” title we print at the top.

format_option_help(formatter)
get_description()
get_option(opt_str)
has_option(opt_str)
remove_option(opt_str)
set_conflict_handler(handler)
set_description(description)
set_title(title)
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: optparse.OptionParser

_add_help_option()
_add_version_option()
_check_conflict(option)
_create_option_list()
_create_option_mappings()
_get_all_options()
_get_args(args)
_init_parsing_state()
_match_long_opt(opt : string) → string

Determine which long option string ‘opt’ matches, ie. which one it is an unambiguous abbreviation for. Raises BadOptionError if ‘opt’ doesn’t unambiguously match any long option string.

_populate_option_list(option_list, add_help=True)
_process_args(largs, rargs, values)
_process_args(largs[string],

rargs : [string], values : Values)

Process command-line arguments and populate ‘values’, consuming options and arguments from ‘rargs’. If ‘allow_interspersed_args’ is false, stop at the first non-option argument. If true, accumulate any interspersed non-option arguments in ‘largs’.

_process_long_opt(rargs, values)[source]

SCons-specific processing of long options.

This is copied directly from the normal optparse._process_long_opt() method, except that, if configured to do so, we catch the exception thrown when an unknown option is encountered and just stick it back on the “leftover” arguments for later (re-)processing.

_process_short_opts(rargs, values)
_share_option_mappings(parser)
add_local_option(*args, **kw)[source]

Adds a local option to the parser.

This is initiated by a SetOption() call to add a user-defined command-line option. We add the option to a separate option group for the local options, creating the group if necessary.

add_option(Option)

add_option(opt_str, …, kwarg=val, …)

add_option_group(*args, **kwargs)
add_options(option_list)
check_values(values : Values, args : [string])

-> (values : Values, args : [string])

Check that the supplied option values and leftover arguments are valid. Returns the option values and leftover arguments (possibly adjusted, possibly completely new – whatever you like). Default implementation just returns the passed-in values; subclasses may override as desired.

destroy()

Declare that you are done with this OptionParser. This cleans up reference cycles so the OptionParser (and all objects referenced by it) can be garbage-collected promptly. After calling destroy(), the OptionParser is unusable.

disable_interspersed_args()

Set parsing to stop on the first non-option. Use this if you have a command processor which runs another command that has options of its own and you want to make sure these options don’t get confused.

enable_interspersed_args()

Set parsing to not stop on the first non-option, allowing interspersing switches with command arguments. This is the default behavior. See also disable_interspersed_args() and the class documentation description of the attribute allow_interspersed_args.

error(msg : string)[source]

Print a usage message incorporating ‘msg’ to stderr and exit. If you override this in a subclass, it should not return – it should either exit or raise an exception.

exit(status=0, msg=None)
expand_prog_name(s)
format_description(formatter)
format_epilog(formatter)
format_help(formatter=None)
format_option_help(formatter=None)
get_default_values()
get_description()
get_option(opt_str)
get_option_group(opt_str)
get_prog_name()
get_usage()
get_version()
has_option(opt_str)
parse_args(args=None, values=None)
parse_args(args[string] = sys.argv[1:],

values : Values = None)

-> (values : Values, args : [string])

Parse the command-line options found in ‘args’ (default: sys.argv[1:]). Any errors result in a call to ‘error()’, which by default prints the usage message to stderr and calls sys.exit() with an error message. On success returns a pair (values, args) where ‘values’ is a Values instance (with all your option values) and ‘args’ is the list of arguments left over after parsing options.

preserve_unknown_options = False
print_help(file : file = stdout)

Print an extended help message, listing all options and any help text provided with them, to ‘file’ (default stdout).

print_usage(file : file = stdout)

Print the usage message for the current program (self.usage) to ‘file’ (default stdout). Any occurrence of the string “%prog” in self.usage is replaced with the name of the current program (basename of sys.argv[0]). Does nothing if self.usage is empty or not defined.

print_version(file : file = stdout)

Print the version message for this program (self.version) to ‘file’ (default stdout). As with print_usage(), any occurrence of “%prog” in self.version is replaced by the current program’s name. Does nothing if self.version is empty or undefined.

remove_option(opt_str)
reparse_local_options()[source]

Re-parse the leftover command-line options.

Parse options stored in self.largs, so that any value overridden on the command line is immediately available if the user turns around and does a GetOption() right away.

We mimic the processing of the single args in the original OptionParser _process_args(), but here we allow exact matches for long-opts only (no partial argument names!). Otherwise there could be problems in add_local_option() below. When called from there, we try to reparse the command-line arguments that

  1. haven’t been processed so far (self.largs), but

  2. are possibly not added to the list of options yet.

So, when we only have a value for “–myargument” so far, a command-line argument of “–myarg=test” would set it, per the behaviour of _match_long_opt(), which allows for partial matches of the option name, as long as the common prefix appears to be unique. This would lead to further confusion, because we might want to add another option “–myarg” later on (see issue #2929).

set_conflict_handler(handler)
set_default(dest, value)
set_defaults(**kwargs)
set_description(description)
set_process_default_values(process)
set_usage(usage)
standard_option_list = []
class SCons.Script.SConsOptions.SConsValues(defaults)[source]

Bases: optparse.Values

Holder class for uniform access to SCons options, regardless of whether or not they can be set on the command line or in the SConscript files (using the SetOption() function).

A SCons option value can originate three different ways:

  1. set on the command line;

  2. set in an SConscript file;

  3. the default setting (from the the op.add_option() calls in the Parser() function, below).

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 should allow 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.

Note that not all command line options are settable from SConscript files, and the ones that are must be explicitly added to the “settable” list in this class, and optionally validated and coerced in the set_option() method.

_update(dict, mode)
_update_careful(dict)

Update the option values from an arbitrary dictionary, but only use keys from dict that already have a corresponding attribute in self. Any keys in dict without a corresponding attribute are silently ignored.

_update_loose(dict)

Update the option values from an arbitrary dictionary, using all keys from the dictionary regardless of whether they have a corresponding attribute in self or not.

ensure_value(attr, value)
read_file(filename, mode='careful')
read_module(modname, mode='careful')
set_option(name, value)[source]

Sets an option from an SConscript file.

settable = ['clean', 'diskcheck', 'duplicate', 'help', 'implicit_cache', 'max_drift', 'md5_chunksize', 'no_exec', 'num_jobs', 'random', 'stack_size', 'warn', 'silent', 'no_progress']
SCons.Script.SConsOptions.diskcheck_convert(value)[source]

SCons.Script.SConscript module

SCons.Script.SConscript

This module defines the Python API provided to SConscript and SConstruct files.

SCons.Script.SConscript.BuildDefaultGlobals()[source]

Create a dictionary containing all the default globals for SConstruct and SConscript files.

SCons.Script.SConscript.Configure(*args, **kw)[source]
class SCons.Script.SConscript.DefaultEnvironmentCall(method_name, subst=0)[source]

Bases: object

A 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, exports, sconscript)[source]

Bases: object

A frame on the SConstruct/SConscript call stack

SCons.Script.SConscript.Return(*vars, **kw)[source]
class SCons.Script.SConscript.SConsEnvironment(platform=None, tools=None, toolpath=None, variables=None, parse_flags=None, **kw)[source]

Bases: SCons.Environment.Base

An 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)
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 existing construction variables in an Environment.

AppendENVPath(name, newpath, envname='ENV', sep=':', delete_existing=0)

Append path elements to the path ‘name’ in the ‘ENV’ 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 0, a newpath which is already in the path will not be moved to the end (it will be left where it is).

AppendUnique(delete_existing=0, **kw)

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

Builder(**kw)
CacheDir(path)
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)[source]
Decider(function)
Default(*targets)[source]
Depends(target, dependency)

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

Detect(progs)

Return the first available program in progs.

Parameters

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

Returns str

first name from progs that can be found.

Dictionary(*args)

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 (optional) – specify the format to serialize to. “pretty” generates a pretty-printed string, “json” a JSON-formatted string. (Default value = None, equivalent to “pretty”)

EnsurePythonVersion(major, minor)[source]

Exit abnormally if the Python version is not late enough.

EnsureSConsVersion(major, minor, revision=0)[source]

Exit abnormally if the SCons version is not late enough.

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

Directly execute an action through an Environment

Exit(value=0)[source]
Export(*vars, **kw)[source]
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='.')

returns a list of all source files.

Flatten(sequence)
GetBuildPath(files)
GetLaunchDir()[source]
GetOption(name)[source]
Glob(pattern, ondisk=True, source=False, strings=False, exclude=None)
Help(text, append=False)[source]
Ignore(target, dependency)

Ignore a dependency.

Import(*vars)[source]
Literal(string)
Local(*targets)
MergeFlags(args, unique=1, dict=None)

Merge the dict in args into the construction variables of this env, or the passed-in dict. If args is not a dict, it is converted into a dict using ParseFlags. If unique is not set, the flags are appended rather than merged.

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=1)

Use the specified function to parse the output of the command in order to modify the current environment. The ‘command’ can be a string or a list of strings representing a command and its arguments. ‘Function’ is an optional argument that takes the environment, the output of the command, and the unique flag. If no function is specified, MergeFlags, which treats the output as the result of a typical ‘X-config’ command (i.e. gtk-config), will merge the output into the appropriate variables.

ParseDepends(filename, must_exist=None, only_one=0)

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)

Parse the set of flags and return a dict with the flags placed in the appropriate entry. The flags are treated as a typical set of command-line flags for a GNU-like toolchain and used to populate the entries in the dict immediately below. If one of the flag 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 existing construction variables in an Environment.

PrependENVPath(name, newpath, envname='ENV', sep=':', delete_existing=1)

Prepend path elements to the path ‘name’ in the ‘ENV’ 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 0, a newpath which is already in the path will not be moved to the front (it will be left where it is).

PrependUnique(delete_existing=0, **kw)

Prepend values to existing construction variables in an Environment, if they’re not already there. If delete_existing is 1, 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)

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).

SConscript(*ls, **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.

SConscriptChdir(flag)[source]
SConsignFile(name='.sconsign', dbm_module=None)
Scanner(*args, **kw)
SetDefault(**kw)
SetOption(name, value)[source]
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, **kw)
Value(value, built_value=None, name=None)
VariantDir(variant_dir, src_dir, duplicate=1)
WhereIs(prog, path=None, pathext=None, reject=[])

Find prog in the path.

_canonicalize(path)
_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)
_copy2_from_cache(src, dst)
_copy_from_cache(src, dst)
_exceeds_version(major, minor, v_major, v_minor)[source]

Return 1 if ‘major’ and ‘minor’ are greater than the version in ‘v_major’ and ‘v_minor’, and 0 otherwise.

_find_toolpath_dir(tp)
_get_SConscript_filenames(ls, kw)[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.

_get_major_minor_revision(version_string)[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()

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

_update(dict)

Update an environment’s values directly, bypassing 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)
get(key, default=None)

Emulates the get() method of dictionaries.

get_CacheDir()
get_builder(name)

Fetch the builder with the specified name from the environment.

get_factory(factory, default='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()
gvars()
has_key(key)

Emulates the has_key() method of dictionaries.

items()

Emulates the items() method of dictionaries.

keys()

Emulates the keys() method of dictionaries.

lvars()
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)

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)

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)

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

values()

Emulates the values() method of dictionaries.

exception SCons.Script.SConscript.SConscriptReturn[source]

Bases: Exception

args
with_traceback()

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

SCons.Script.SConscript.SConscript_exception(file=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>)[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._SConscript(fs, *files, **kw)[source]
SCons.Script.SConscript.annotate(node)[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_DefaultEnvironmentProxy()[source]
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, must_exist=None)[source]

Take appropriate action on missing file in SConscript() call.

Print a warning or raise an exception on missing file. On first warning, print a deprecation message.

Parameters
  • f (str) – path of missing configuration file

  • must_exist (bool) – raise exception if file does not exist

Raises

UserError if 'must_exist' is True or if global – SCons.Script._no_missing_sconscript is True.

Module contents

SCons.Script

This file implements 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=False)[source]
class SCons.Script.TargetList(initlist=None)[source]

Bases: collections.UserList

_UserList__cast(other)
_abc_impl = <_abc_data object>
_add_Default(list)[source]
_clear()[source]
_do_nothing(*args, **kw)[source]
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.Variables(files=None, args={})[source]
SCons.Script._Add_Arguments(alist)[source]
SCons.Script._Add_Targets(tlist)[source]
SCons.Script._Get_Default_Targets(d, fs)
SCons.Script._Set_Default_Targets(env, tlist)[source]
SCons.Script._Set_Default_Targets_Has_Been_Called(d, fs)[source]
SCons.Script._Set_Default_Targets_Has_Not_Been_Called(d, fs)[source]
SCons.Script.set_missing_sconscript_error(flag=1)[source]

Set behavior on missing file in SConscript() call. Returns previous value