Defining commands
Introduction
While standard command-line utilities generally have a single purpose (i.e. rm removes files, ls lists files, etc.), more complex programs often have different commands built into one executable (i.e. git can push, pull, or commit, docker can build, start, or stop, and apt can install, list or remove, etc.)
The argumentor library makes it possible to define several commands (like git and docker do) into a single executable. Each command can then have its own set of options (i.e. git push supports several options, such as -u, -f, that are not necessarily supported by other git commands).
Commands
Using argumentor, a command can be defined using the Argumentor.add_command method:
from argumentor import Argumentor
argm = Argumentor()
argm.add_command(
"list",
description="list all things"
)
Aliases
Aliases are another nice feature of argumentor. They allow a command to be called using different names. The most frequent use case would be to have a short version of an existing command (i.e. allowing the user to use l instead of list). It is possible to define multiple aliases for a single command.
A command alias can be defined using the Argumentor.add_command_alias method:
from argumentor import Argumentor
argm = Argumentor()
argm.add_command(
"list",
description="list all things"
)
argm.add_command_alias("l", "list")
Expected values
Commands (as well as their aliases) can expect different types of values. The default one is bool, which means that its value will be set to True when the command is present in the user command-line input. However, the following types are supported as well:
bool: the default type, will be set toTrueif the command is presentstr: the command expects a stringint: the command expects a positive integerlist: the command expects one or more strings
When the Argumentor.parse() method is called, values are automatically converted to their expected type. Any problem during the conversion will raise a fatal error (ParsingError).
Below is an example of a command that expects a list of strings as its value:
#!/usr/bin/env python3
import sys
from argumentor import Argumentor
from argumentor.exc import ParsingError
argm = Argumentor()
argm.add_command(
"foo",
value_type=list,
)
try:
cmd, opts = argm.parse()
except ParsingError as err:
print(err)
sys.exit(1)
print("command: ", cmd)
print("options: ", opts)
Running the program above will result in: