Home Programming Basics of Parsing Command Line Arguments in Python

Basics of Parsing Command Line Arguments in Python

by Roshan Agarwal
Parsing command-line arguments in python

Command-line applications are one of the oldest and most used types of apps. If you are an experienced Linux user, you may have hardly used GUI tools instead of command-line tools to do the same task. For example, Anaconda, the package manager for python, has command-line tools named Conda and GUI tool named anaconda navigator.

The thing that makes the Command-line application popular among developers is that they consume very few resources compared to its GUI counterpart and give better performance.

Python is a simple and powerful language for building command-line applications. It provides tons of libraries already written by many great programmers, making our task easier as we don’t need to rewrite the same code.

In this tutorial, I will present the python’s Argparse library to you, which can parse arguments of the command line applications. This is useful for building great command-line interfaces. To follow this tutorial, it is recommended to have the latest version of python installed. We also have a step by step tutorial on updating python to the latest version in Linux.

Introduction

Argument Parsing is an important concept we must use to build powerful and user-friendly command-line interfaces. If you have used command-line applications earlier, you may have noticed that we can add arguments to the command line applications to configure the tool’s options.

For example, if you have used the ls command in Linux, which is used to list the current working directory items, you may have seen output something similar, as shown in the below image.

ls command in linux

ls command in Linux

As you can see in the image, it lists the items in the current directory. We can also use the ls command more beneficially by giving it an argument as I did in the following command.

ls -a

Now on typing this command in the terminal, it will list all the items present in the current working directory, including the hidden items. As you can see, by providing arguments on the command, we can easily specify options to the command in a friendly way. This is where arguments come into play. They make the Command line applications more useful and friendly.

You may be wondering when and how to add command-line arguments in your applications. Imagine you are building an application that needs a user input of the filename that the application will process.

We can do it in two ways:

  • by prompting the user to add the file name or
  • by providing the user to add the file name as an argument to the command.

The first trick is good, but the second one is more useful as the user can give all the options in one command, which makes it more user-friendly.

Python includes a great library named “argparse,” which is useful for creating and parsing command-line arguments and can build powerful command-line interfaces for the users very easily. Let us take a deep dive into the python’s argparse library.

Argparse library

The argparse library is an easy and useful way to parse arguments while building command-line applications in python. Although there are other arguments parsing libraries like optparse, getopt, etc., the argparse library is officially the recommended way for parsing command-line arguments.

It is also available in the python’s standard library, so we don’t need any manual configuration. The argparse library has been build using the optparse library of python, but argparse is more useful and developers friendly than the optparse library.

Practical Demo of Argparse

Let us see a practical demo of how to use the argparse library for creating a simple command-line interface. This program will accept a path and check whether the path exists or not and if it exists, then print whether it is a file or a directory.

import os
import argparse

parser = argparse.ArgumentParser(`description = "Path Existence Checker")
parser.add_argument("--path", help="input a path to check if it exists")
args = parser.parse_args()
input_path = args.path
if os.path.isdir(input_path):
    print("The path Exists and it is a directory")
elif os.path.isfile(input_path):
    print("The path Exists and it is a file")
else:
    print("The path does not exist")
On running the above program, we can check if the path exists or not.
demo of parsing arguments with argparse

demo of parsing arguments with argparse

You can also use the -h argument with the program, which is the default argument for displaying help messages.
argparse default help message

argparse default help message

Let me explain to you how the above program works. In the first two lines, we imported the modules which we will require in the program. The os module has been imported to check if the path exists or not, and is it a file or a directory. If you want to learn more about the os module, you can refer to our guide on working with os in python.
In the next line, we imported the argparse library required to create and parse arguments. In the third line, we create a parser object using the ArgumentParser class of the argparse library. This class also accepts an optional parameter description, which will be displayed in the help message.
In the next line, we have created an argument named path using the add_argument() method of the parser object and give the detail in the help parameter that will be displayed in the help message as we have seen in the output earlier.
Next, we parse the arguments using the parse_args() method of the parser object and access the user input path as an argument. We got the path that the user input in the argument and then used it with the os module to check if it is a file or folder. If it is not among the two, it will print that the path does not exist.

Customization

Let us see some of the customizations that we can do to our command-line interface with the help of argparse library.

Custom Usage help

When we run the demo program that we created earlier with the -h parameter, we get the program’s help as the output that the argparse library generated. If you notice the help message, there is a usage help in the top line that shows us how to use it.
In our demo program, we have got the standard usage help. We can still easily customize it by using the usage parameter while creating the parser object using the ArgumentParser() class. Look at the below code, which shall be modified in our demo program.
parser = argparse.ArgumentParser(description = "Path Existence Checker", usage="cla.py path")
Here is the output:
custom usage help in argparse

custom usage help in argparse

As we can see in the output, the usage help has been changed to the one we specify in the ArgumentParser() class usage parameter.

Customizing Arguments

We can also use the Argparse library to customize the arguments like is the arguments will be required or not, giving an argument a default value.

Adding default value

We can give the arguments a default value using the default parameter to the add_argument() method. For example, see the below code.

import os
import argparse

parser = argparse.ArgumentParser(description = "Path Existence Checker", usage="cla.py path")
parser.add_argument("--path", help="input a path to check if it exists", default="filename.txt")
args = parser.parse_args()
input_path = args.path

if input_path == None:
    exit()
elif os.path.isdir(input_path):
    print("The path Exists and it is a directory")
elif os.path.isfile(input_path):
    print("The path Exists and it is a file")
else:
    print("The path does not exist")

On running the above program without any argument, we will get the below output. As shown in the output, the program checks the path filename.txt, which we set in the default parameter.

giving a default value to arguments

giving a default value to arguments

Setting Requirements of Arguments

We can also use the Argparse library to set the argument’s requirements, i.e., whether the arguments will be necessary or not. To do so, we need to use the required parameter, as shown in the below code.

import os
import argparse

parser = argparse.ArgumentParser(description = "Path Existence Checker", usage="cla.py path")
parser.add_argument("--path", help="input a path to check if it exists", default="filename.txt", required=True)
args = parser.parse_args()
input_path = args.path

if input_path == None:
    exit()
elif os.path.isdir(input_path):
    print("The path Exists and it is a directory")
elif os.path.isfile(input_path):
    print("The path Exists and it is a file")
else:
    print("The path does not exist")

On running the above code without any arguments, you will get an error saying the following arguments are required.

setting the requirements of arguments

setting the requirements of arguments

Type of Argument

We can also set the Data Type used in the argument. For example, if we need the path, we should give a string data type. If a user enters a data type that is not a string, Argparser will change it into a string. To set the default type for an argument, run the below code.

import os
import argparse

parser = argparse.ArgumentParser(description = "Path Existence Checker", usage="cla.py path")
parser.add_argument("--path", help="input a path to check if it exists", type=str)
args = parser.parse_args()
input_path = args.path

if input_path == None:
    exit()
elif os.path.isdir(input_path):
    print("The path Exists and it is a directory")
elif os.path.isfile(input_path):
    print("The path Exists and it is a file")
else:
    print("The path does not exist")

Output:

specifying the data type of arguments

specifying the data type of arguments

Conclusion

This is only the basics of parsing arguments using the Argparse library. After going through this tutorial, it is recommended to read the official documentation to explore more tricks of using this library. You may also want to see the post on using logging in python, which is very useful for writing big applications and easy debugging.

You may also like

Leave a Comment

fl_logo_v3_footer

ENHANCE YOUR LINUX EXPERIENCE.



FOSS Linux is a leading resource for Linux enthusiasts and professionals alike. With a focus on providing the best Linux tutorials, open-source apps, news, and reviews written by team of expert authors. FOSS Linux is the go-to source for all things Linux.

Whether you’re a beginner or an experienced user, FOSS Linux has something for everyone.

Follow Us

Subscribe

©2016-2023 FOSS LINUX

A PART OF VIBRANT LEAF MEDIA COMPANY.

ALL RIGHTS RESERVED.

“Linux” is the registered trademark by Linus Torvalds in the U.S. and other countries.