Skip to content

Ferdinand Agyei-Yeboah

Reading Python Command Line Arguments Using ArgParse

January 08, 2019

Most meaningful scripts require or will benefit from the ability to pass in options. In Python, Argparse is a built in module that makes configuring and reading options for a script a breeze. It allows you to achieve the syntax many cli tools use for passing options, such as –version.

Using Argparse

To use argparse, we import the argparse library, create an ArgumentParser instance and then configure our program arguments.

import argparse
parser = argparse.ArgumentParser(description='This program deploys an application.')
parser.add_argument("--name", action="store", required=True, help="Name of application to deploy" )
parser.add_argument("--version", action="store", type=float, default="1.0.0", help="Version of application" )
parser.add_argument("--environment", default="QA", choices=["DEV", "QA", "PROD"], help="Application environment" )
args = parser.parse_args()
print("Deploying {} v{} to the {} environment!".format(args.name, args.version, args.environment))

We use the add_argument() method on the parser to configure each command line option. In the action property we specify what we want to occur for each parameter, the default is store, which captures the user input as a field on the parser. We can configure other properties such as the type of option (int, string, float, etc), if it is required or not, any restricted values (choices) and so on. We call parser.parseargs() to populate the values of all the options and then use args.[option_name]_ to pull off the option we want to read.

Using the -h option shows the user how to use the script.

Help output

Now lets run our program with our defined options.

Help output

We can see all our options are successfully received and printed.

A few of the benefits of using argparse can clearly be seen

  • The arguments can be passed in any order as long as the key and value pairs match.
  • The script is self documenting and guides users on its usage.
  • The script is self validating. Users are notified when they do not pass required parameters and are informed when there is only a subset of options to choose (i.e DEV, QA and PROD for environment).

There is much more you can do with argparse. If you want to learn more about argparse, you can check out the official docs.


Software Engineering Tutorials & Best Practices