xobox’ Command Line Interface¶
xobox’ command line interface is contained within the xobox.cli
package. It offers only one function at
package level which can be called directly. This function is usually called from a Python script acting as executable
interface.
-
xobox.cli.
execute
(argv=None)[source]¶ Function being called from the executable to launch the CLI. This is the initial entrance point for any xobox processing. Usually, this function is invoked by an executable Python script to start the actual xobox CLI process. This could look like the following example:
import sys from xobox.cli import execute sys.exit(execute(sys.argv))
Parameters: argv (list) – list of (command line) arguments The
execute()
function will create aCommandDispatcher
instance, which provides the logic for invoking a command.
Dispatcher¶
-
class
xobox.cli.dispatch.
CommandDispatcher
(argv=None)[source]¶ Class encapsulating the logic for starting a command.
Parameters: argv (list) – list of (command line) arguments -
execute
()[source]¶ Based on the given command line arguments and the available subcommands, this method creates the appropriate command line parser and starts the corresponding subcommand.
-
status
¶ Exit status
-
Command Line Commands¶
Command line commands are implemented as modules within the xobox.cli.commands
package.
The module name itself must be unique within the commands
package, but has no
direct link to the command’s external designator used on the command line.
All command line commands are implemented as classes, inheriting from xobox.cli.base.BaseCommand
:
-
class
xobox.cli.base.
BaseCommand
(global_args=None, cmd_args=None, logger=None)[source]¶ The base class from which all CLI commands derive.
Attributes affecting the behaviour of a Command object:
help
- A short description of the command, which will be used to construct help messages or usage instructions for the command.
name
- The name under which the command is known. Internally, the name only differs from an alias in the fact that it’s used as the “main” alias in help and usage messages.
aliases
- A tuple of alias names for the command
arguments
- A tuple of arguments accepted by the command. Each argument
consists of a tuple with two elements.
The first element is a tuple containing the short and long
option identifiers; e. g. (‘-f’, ‘–foo’)
The second element is a dictionary containing arbitrary elements.
All keyword arguments accepted by
argparse.ArgumentParser.add_argument()
are allowed as key names within this dictionary.
-
execute
()[source]¶ Set up environment for running the command. Then call the handle() method which needs to be implemented by each command.
Writing a Command Line Command¶
Writing a command line command can be as easy as creating a Python module within the
xobox.cli.commands
package containing a class inheriting from
BaseCommand
and overriding some basic settings:
from xobox.cli.base import BaseCommand
class MyCommand(BaseCommand)
name = 'foo'
aliases = ('bar', 'baz')
help = 'The super foo command that makes you bar'
Looks easy? It actually is, since CommandDispatcher
is performing all the black magic needed to detect available commands, make up decent usage
messages out of the information provided by each command’s implementation, parsing eventual
command line arguments required by the different commands and finally setting up the environment
and running the command.
Unfortunately, this command would not be of any use – once invoked by the dispatcher, it will
simply raise a NotImplementedError
exception. This is simply for the fact that each
command needs to implement its own handle()
method.
Since this has not happened here, the handle()
method
inherited from the CommandDispatcher
class will be used, and
this one simply raises a NotImplementedError
exception.
When implementing your own handle()
method, please
take care of the following conventions.
User Interaction¶
Whenever possible, user interaction shall be avoided. The concept of xobox is to gather all required information either form command line arguments or from configuration files, and then to run silently, only outputting status information according to the log level set by the user.
This restriction has been set in order to respecting that one important use case is to run xobox as batch job, where no user interaction is possible.
Output¶
All output to the user interface shall be channelled through the appropriate log_...()
methods
each command class has inherited from the BaseCommand
class.
This ensures the output is only sent if the user has selected the corresponding log level, and it
is sent through the right channel.
Warning
Never use Python’s print()
function to generate and send output to the user
interface. This will break xobox’s promise of being 100% batch job enabled, including
logging its output to a file.
Status¶
xobox uses the status
property any command
has inherited from the BaseCommand
class for setting an
appropriate exit status when terminating xobox’s main process.
By default, a command object’s status is set to os.EX_OK
. If necessary or appropriate, the
status information can be changed within the handle()
method
by overwriting the internal _status
member:
def handle(self):
self._status = xobox.utils.compat.EX_USAGE
Existing Command Line Commands¶
Version Command¶
-
class
xobox.cli.commands.version.
VersionCommand
(global_args=None, cmd_args=None, logger=None)[source]¶ Command class implementing the version command.
-
aliases
= ('--version', '-v')¶
-
arguments
= ((('-s', '--short'), {'help': 'only print the version string', 'action': 'store_true'}),)¶
-
help
= 'Show version and copyright information'¶
-
name
= 'version'¶
-
Logging Interface¶
The logger
module is responsible for handling any
output that shall be transported to the user. It implements the magic behind
the log_...()
methods provided by the CommandDispatcher
class, allowing command implementations to easily transporting information to the user interface.
The logger
module provides a class interface,
offering a flexible message output system:
-
class
xobox.cli.logger.
Logger
¶ -
get_instance
(*args, **kwargs)¶ Obtain the reference to the instance of
Logger
. If no instance exists yet, one will be created and its reference returned.Warning
If a logger instance already exists (e. g. due to an earlier invocation from another module or function), any passed keyword arguments will be ignored. Therefore, it is safer to not using any keyword arguments, but setting the logger’s properties appropriately after having received the logger instance’s reference.
-
log
(level, message)¶ Register a log message within the logging queue and flush the queue afterwards (currently log messages are not cached).
Parameters:
-
log_error
(message)¶ Convenience shortcut for registering messages with log level error
Parameters: message (str) – The message string to be recorded
-
log_warning
(message)¶ Convenience shortcut for registering messages with log level warning
Parameters: message (str) – The message string to be recorded
-
log_notice
(message)¶ Convenience shortcut for registering messages with log level notice
Parameters: message (str) – The message string to be recorded
-
log_info
(message)¶ Convenience shortcut for registering messages with log level info
Parameters: message (str) – The message string to be recorded
-
log_debug
(message)¶ Convenience shortcut for registering messages with log level debug
Parameters: message (str) – The message string to be recorded
-
log_usage
(message)¶ Convenience shortcut for registering messages with log level usage
Parameters: message (str) – The message string to be recorded
-
color
¶ Boolean switch indicating whether this logger allows colored output.
-
file
¶ The log file used when run as file logger. Must be a string indicating the path name of the file to log into.
-
level
¶ The log level (string). Expected to be one of mute, error, warning, info or debug.
-
type
¶ The logger type (string). Expected to be one of term or file.
-