Posted in Python, Python Libraries

[Python] Quick Intro To Argparse

The Argparse library is an elegant way to parse command line arguments in Python. At some point in your coding career, you might have done something like this.

import sys

if __name__ == '__main__':

    if len(sys.argv) < 3:
        print("Usage my_script.py <param1> <param2>")
        sys.exit(1)

The above code snippet checks whether a user ran the python script my_script.py with less than 3 command line arguments. If so, it prints an error message and exits the program. This is a perfectly fine way to handle command line arguments in Python. What is missing?

  • We need to explicitly check whether the user provided sufficient arguments
  • Check whether all the arguments are of the correct data type
  • Print usage/ help and error statements manually

The Argparse module in Python helps us write user-friendly command-line interfaces. One of the best aspects of it is the auto-generation of usage and help messages as well as error handling when insufficient arguments or arguments of the wrong data types are provided by the user. Let’s look at a simple example.

import argparse

if __name__ == "__main__":

    parser = argparse.ArgumentParser(description="Read a file and remove a given list of users")

    parser.add_argument(
        'file',
        type=str,
        help='Path to the input file')

    parser.add_argument(
        '-l',
        '--list',
        help='List of users to remove',
        type=str,
        required=True)

    args = parser.parse_args()
    file_path = args.file
    users = args.list

Now try running the above code snippet without any arguments. The code will throw an error as shown below.

$ python my_scipt.py
usage: my_script.py [-h] -l LIST file
my_script.py: error: the following arguments are required: file, -l/--list

Try using -h or –help to find out more about the usage of this file. You will see something like this. Beautiful, isn’t it?

$ python my_script.py -h
usage: my_script.py [-h] -l LIST file

Read a file and remove a given list of users

positional arguments:
  file                  Path to the input file

optional arguments:
  -h, --help            show this help message and exit
  -l LIST, --list LIST  List of users to remove

What this tells you is that the script should be run with two arguments.

  • file
  • – l “user1, user2, user3”

Let’s dive into how argparse works.

Create a parser

import argparse

parser = argparse.ArgumentParser(
             usage="Example usage: my_script.py [-h] -l 'user1, user2, user3' file_path"
             description="Read a file and remove a given list of users",
         )
  • Import argparse into your Python program.
  • argparse.ArgumentParser creates an ArgumentParser object. This parses the command line arguments into Python data types. A couple of useful parameters are description and usage fields.
    • description gives a brief summary of the functionality offered by the script.
    • usage overrides the default program usage printed on the terminal, with your message.

Add arguments to the parser

parser.add_argument(
    'file',
    type=str,
    help='Path to the input file')

parser.add_argument(
    '-l',
    '--list',
    help='List of users to remove',
    type=str,
    required=True)
  • You can see from the above output that argparse allows positional (file) and optional arguments (-l, –list, -h). The parameter required can be set to True to mark an optional argument as required. In the above example -l or –list which refers to the list of users to be removed is a required option from the user. Add argument also allows the usage of shorthand arguments like -l, -h similar to what we see in bash scripts.
  • Only optional arguments can be omitted. Positional arguments are compulsory and do not allow the setting of required parameter.
  • type refers to the Python type to which the argument should be converted. In the above example we are reading the contents that follow -l as a Python string. We can process this string later to get the individual users.
  • help gives a brief description of the argument.

Parse the arguments

args = parser.parse_args()
file_path = args.file
users = args.list.split(",")

parse_args() converts argument strings to objects and assigns them as attributes. The default set of arguments are taken from sys.argv.

Hope you enjoyed this quick intro on getting started with the argparse library. For detailed reading, check out Python docs. Have a great day!