Parsing the command line with argparse
The general approach to using argparse
involves four steps.
Create
ArgumentParser
. We can provide you with overall information about the command-line interface here. This might include a description, format changes for the displayed options and arguments, and whether or not-h
is the "help" option. Generally, we only need to provide the description; the rest of the options have sensible defaults.Define the command-line options and arguments. This is done by adding arguments with the
ArgumentParser.add_argument()
method function.Parse the
sys.argv
command line to create a namespace object that details the options, option arguments and overall command-line arguments.Use the resulting namespace object to configure the application and process the arguments. There are a number of alternative approaches to handle this gracefully. It may involve parsing configuration files, as well as command-line options. We'll look at several designs.
An important feature...