How to Parse Arguments from the Command Line using argparse in Python 3


argparse in python
Intermediate

Having command line parameters is an essential mechanism to manage the behaviour of your application but it can get complex to validate and extract the arguments. In our previous article on arguments (How to use argv parameters in Python), we went over how to use command line parameters with sys.argv. This is a useful module, but we will come across cases where we want to do more than just that. If you code enough in Python, you are most likely going to want to let users provide values for variables at runtime.

This is where argparse comes in. In this article, we are going to look into argparse – what it is. why we use it and how we parse arguments using it.

NOTE: This article assumes you have some Python knowledge and understand command line arguments.

argparse is a python module whose primary purpose is to create command line interfaces. This module was released as a replacement for the getopt and optparse modules because they lacked some important features.

The Python argparse module:

  • Allows the use of positional arguments
  • Allows the customization of the prefix chars
  • Supports variable numbers of parameters for a single option

What is a Command Line Interface (CLI)?

Before we start making use of argparse to build our own command line interfaces, let’s take a brief look at what a command line interface is. If you have used the terminal or command prompt you have probably already used a command line interface.

Below we open a folder and run the ls command to get the list of files in the directory we are in

There are some files in this directory but not a lot of information about them. Let’s add some arguments to ls. We will run the same command and parse -l to it.

Adding that argument gives us more information about the files. This works by accessing the options present in the ls command line interface. Now that we have a general idea of CLIs we can start making our own.

If your goal is to provide a user-friendly approach to your program, it is usually a good idea to implement a CLI

How to Parse Arguments with argparse

To understand how argparse works and how we go about making our own command line interfaces, we will begin with a simple example illustrated below:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-n", "--name", required=True)
args = parser.parse_args()
print(f'Hi {args.name} , Welcome ')

Confusing? Yes, I know. But let’s break this down line by line:

  • We initially import the argparse module
  • We then initialize the ArgumentParser object as parser
  • We add the only argument –name, here we must specify both the shorthand and longhand versions. Either can be used when the program is run
  • We stipulate that this argument is required
  • We execute the parse_args() method
  • We output the parsed argument

We get the output of our print statement plus the parsed argument. But what would happen if we ran the program but didn’t give any arguments? We will try that next:

We got an error message, explaining the usage of the program and the arguments that are required. But we never added that to our code, did we? Well, not explicitly. When we added arguments for the program, argparse generates the error message if those arguments ate not given.

Looking at the output once again, you will notice there is another argument, one that we did not give -h. This is an optional argument that the program accepts. It serves as a sort of help command to describe what is required by the program.

Let’s parse that argument to see what output we get:

As we see, parsing the -h argument gives a bit more detailed explanation of the program. Armed with a basic understanding of argparse we can look at another example.

We are going to code our own program that simulates the same operation as ls:

# Import the argparse library
import argparse

import os
import sys

my_parser = argparse.ArgumentParser(description='List all the contents of a folder')

my_parser.add_argument('Path',
                       metavar='path',
                       type=str,
                       help='the path to list')

args = my_parser.parse_args()

input_path = args.Path

if not os.path.isdir(input_path):
    print('The path specified does not exist')
    sys.exit()

print('\n'.join(os.listdir(input_path)))

We need to import a number of modules first namely os, sys, and argparse. After that we:

  • create the parser and assign it the name my_parser
  • add the necessary arguments – in this case, path. We also specify the type of the argument as string which tells argparse to check the type automatically
  • execute the parse_args() function
  • create a variable named input_path and assign it args.Path – calling path on the parser
  • run a check if the parsed directory does not exist and display an error message if it doesn’t
  • we output the inputted directory

We are running the program on the same directory as before:

We get an output with the same files.

How to Customize Your CLI with argparse

The argparse module also allows us to customize our CLI. We have already done something of the sort in the last example. When we created the parser object: my_parser = argparse.ArgumentParser(description='List all the contents of a folder')

In this case, description, which gives an explanation of the program which is outputted when we run the -h/--help argument. In addition to description, there are two other ways we can use to customize our parser:

  • prog: which gives our program a custom name replacing sys.argv[0]
  • epilog: text which displayed after help text

Let’s add these to our first example:

import argparse

parser = argparse.ArgumentParser(prog='greeting', 
                                description='Greets the user', 
                                epilog='Thank you for using the program. Have a nice day')

parser.add_argument("-n", "--name", required=True)
args = parser.parse_args()
print(f'Hi {args.name} , Welcome ')

We ran our program, parsed the –help argument and we the name we gave, description and epilog are all output.

Final example with argparse

Let’s say you wanted to make a script that would write text to a file, that would look something like this:

import argparse

parser = argparse.ArgumentParser(description='Write to file')


parser.add_argument('file', help='file to store text in')
parser.add_argument('text', help='text to be written to file')

args = parser.parse_args()


print('Writing to: {}'.format(args.file))
print('\t {}'.format(args.text))

with open(args.file, 'w') as my_file:
    my_file.write(args.text)

print('File has been written')

After importing argparse and creating our parser we:

  • add two arguments – one for the file, the other for the data to be written to it
  • execute parse_args()
  • invoke the with() funnction to open the file – parsed as the first argument – in write mode
  • write the second argument to the file
  • the print statements are so we see what is happening – they can be omitted

NOTE: If you surround arguments in quotation marks they are treated as though they are one argument.

IMPORTANT: When you add arguments to your parser they become positional arguments and must be parsed in that exact same order

Get Notified Automatically Of New Articles

Want to see more useful articles? Subscribe to our newsletter!

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Content