Using Bases

While the Command is what wraps the main logic of your program, Bases are responsible for parsing options, providing help, and actually running the commands.

Single-Command Base

If your program does not need multiple subcommands, you can just use a SingleBase. It does not require as much configuration as a MultiBase, as it gets most of its information from its Command.

class clap.base.SingleBase(command, program_name=None)

This kind of Base accepts one Command, and you give it during construction. To run it, you call run() with the arguments.

By default, its use_help attribute is True. This injects a -h/--help option into the options list which will display help when encountered.

Parameters:
  • command – The clap.command.Command to use.
  • program_name – The name to use for the program in usage messages. It defaults to the basename of the script’s path.
callback(parser, option, value=None)

This is used as a callback when parsing options. If it returns something other than None, the value will not be stored.

Parameters:
help_message
The message to print on a usage error if use_help is False.
run(argv=None)
This is the entry point for running the program. Call this with the command-line arguments (or not, in which case it will use sys.argv[1:]), and it will handle parsing options and invoking the command.
use_help
Whether to add a “help” option or not

Often, using a SingleBase to run your command is as simple as:

if __name__ == '__main__':
    base = SingleBase(CommandClass)
    base.run()

Multi-Command Base

On the other hand, multiple-subcommand programs along the lines of hg or svn need the MultiBase.

class clap.base.MultiBase(program_name=None)

This base handles programs with multiple “subcommands”, like hg, git, or svn. You add commands with the add_command() method. Like SingleBase, call run() to run the program.

By default, its use_help attribute is True. This injects a help command into the commands list, which will give information on the entire program or just a certain command.

Parameter:program_name – The name to use for the program in usage messages. It defaults to the basename of the script’s path.
add_command(command)

This adds a command to the commands list. The command’s name will override other commands already named or aliased as such, but its aliases will not.

Parameter:command – Either a Command class or an instance thereof.
callback(parser, option, value=None)

This is used as a callback when parsing options. If it returns something other than None, the value will not be stored.

Parameters:
global_defaults
Defaults for global options.
global_options
Options that apply to all commands.
help_message
The message to print on a usage error if use_help is False.
long_desc
A long description of the program.
run(argv=None)
This is the entry point for running the program. Call this with the command-line arguments (or not, in which case it will use sys.argv[1:]), and it will handle parsing options and invoking the command.
use_help
Whether to add a “help” option or not

However, it is often better to create your own subclass of MultiBase to use in your application. For example, the “todo.py” demo application uses this code for its base:

class TodoBase(MultiBase):
    long_desc = """This is a simple to-do list manager. It uses a simple \
text file, and you can mark tasks as high, normal, or low priority."""
    global_options = (
        Option('f', 'file', argument=True, desc="The to-do list file "
               "(defaults to ~/.todolist"),
        Option('v', 'verbose', desc="Print more output than normal")
    )
    global_defaults = dict(
        file=os.path.expanduser('~/.todolist'),
        verbose=False
    )

The Base Class

Both SingleBase and MultiBase are derived from a single class, Base. If you want to write a command-line application working on completely different principles, you can subclass from this to gain some useful utilities.

class clap.base.Base

This is the base class for Bases. It handles the stuff common to both kinds of Base.

TRACEBACK_EXIT_CODE
The exit code to use when a traceback is caught. The default is 120, because it is a nice round number out of the way of special codes.
exit(code=0)
This is called to exit the program, optionally with an error code. You can override this to do something before shutting the program down.
help_formatter_class
The subclass of clap.help.BaseHelpFormatter to format help with.
parse(*args, **kwargs)
This invokes the clap.parser.parse() function with the given arguments and keyword arguments, but it catches errors and uses the parser class specified by parser_class.
parser_class
The parser class to parse arguments with.
print_traceback(err=None)
This is called with the exception when an exception inheriting from Exception is caught while the command is being run. By default, it displays “An error has occurred.” and prints the traceback. You may want to override this so you can hide the traceback from your users, or display a message about the traceback.
run_command(cmd, *args, **kwargs)

This will run a command with the given positional and keyword arguments, automatically catching ScriptError and other kinds of Exception. If you want to provide additional arguments to your commands, you can override this method and use Base.run_command(self, cmd, whatever). (The actual Base classes always call it with the options dictionary and arguments list.)

Parameters:
  • cmd – The command to run.
  • args – Extra positional arguments.
  • kwargs – Extra keyword arguments.

Table Of Contents

Previous topic

Writing Commands

Next topic

Parsing Options

This Page