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] :
-
Initialize
-
Configure
-
Parse
-
Use
For example, using argparse
:
-
Initialize
import argparse
-
Configure
parser = argparse.ArgumentParser() parser.add_argument(...) ...
-
Parse
args = parser.parse_args()
-
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
- I was inspired by the Matplotlib for beginners handout. It is part of a series