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 program is not specified, then sys.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 name parameter will used as the key in the dict that the parse method returns and to create the long flag for the CLI.

The description parameter, if specified, is what will be shown in the help page beside the option’s flags.

The shorthand parameter, if specified, will be used to create the short flag for the CLI. Must be 1 a character-long string.

The call parameter, if specified, will be called from the parse method, if the option was set by the user. The default help option sets it to the print_help_and_exit method of Captain.

parse(args: list[str] = None) tuple#

Parses args, or sys.argv if args is not specified.

The function’s return tuple dependends on the specified ship and whether any options were added.

If the specified ship was 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 ship was 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.exit with the appropriate exit code.

on_usage_error(message: str, command: str = None)#

Prints the error message and calls sys.exit with 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