Key steps to build a CLI

Creating a command-line interface (CLI) for a Python program has become easier to me when I see it as these keys steps [1] :

  1. Initialize

  2. Configure

  3. Parse

  4. Use

For example, using argparse:

  1. Initialize

    import argparse
    
  2. Configure

    parser = argparse.ArgumentParser()
    parser.add_argument(...)
    ...
    
  3. Parse

    args = parser.parse_args()
    
  4. Use

    if args.attribute:
      # do something
    

When the configure step has many commands, I use a function:

def config_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument(...)
    ...
    return parser

and step 2. becomes:

parser = config_parser()

References

  1. I was inspired by the Matplotlib for beginners handout. It is part of a series