Captain#
API#
- class libjam.Captain(ship: object, program: str = None, *, add_help: bool = True, compact_help: bool = None)#
Creates a CLI around a given function or object.
If the
programis not specified, thensys.argv[0]will be used to determine the name of the program.- add_option(name: str, description: str = None, shorthand: str = None, call: callable = None)#
Adds an option to the CLI.
The
nameparameter will used as the key in thedictthat theparsemethod returns and to create the long flag for the CLI.The
descriptionparameter, if specified, is what will be shown in the help page beside the option’s flags.The
shorthandparameter, if specified, will be used to create the short flag for the CLI. Must be 1 a character-long string.The
callparameter, if specified, will be called from theparsemethod, if the option was set by the user. The default help option sets it to theprint_help_and_exitmethod ofCaptain.
- parse(args: list[str] = None) tuple#
Parses
args, or sys.argv ifargsis not specified.The function’s return tuple dependends on the specified
shipand whether any options were added.If the specified
shipwas a function then the returned tuple will look like(funtion_args: list,). If, however, any options were added, then return tuple will be(funtion_args: list, options: dict).If the specified
shipwas an initialised object, then the output will be(function: callable, funtion_args: list). And, naturally, if any options were added then the tuple will look like this(function: callable, funtion_args: list, options: dict).
- build_help() str#
Builds the help page.
- print_help()#
Prints the help page.
- print_help_and_exit()#
Prints the help page and calls
sys.exitwith the appropriate exit code.
- on_usage_error(message: str, command: str = None)#
Prints the error message and calls
sys.exitwith the appropriate exit code.
- on_missing_arguments(args: list, command: str = None)#
Prints the missing arguments and returns the appropriate exit code.
Simple example#
example.py file:
from libjam import Captain
def shout(text: str):
'Shouts the given text back'
if opts.get('world'):
text += ' world'
print(text + '!')
captain = Captain(shout, program='shout')
captain.add_option(
'world', ['world', 'w'],
"Adds ' world' before the exclamation mark",
)
global opts
args, opts = captain.parse()
shout(*args)
Here is what the user will see when running this CLI:
$ ./example.py
shout: missing argument <TEXT>
$ ./example.py Hello
Hello!
$ ./example.py Hello --world
Hello world!
$ ./example.py --help
Usage:
shout [OPTION]... <TEXT>
Description:
Shouts the given text back
Options:
-w, --world - Adds ' world' before the exclamation mark
-h, --help - Prints this page