Basics of Parsing Command Line Arguments in Python

We shall learn about Python's Argparse library, which can parse arguments of the command line applications. It is useful to build great command-line interfaces.

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.

Roshan Agarwal
Roshan Agarwal is a python programmer and Linux lover; he is using and experimenting with python for a long time. He loves to write and review open-source software, command-line tools, and web applications. Apart from writing tutorials, he explores and contributes to open-source programs in GitHub.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

STAY CONNECTED

23,241FansLike
399FollowersFollow
16SubscribersSubscribe

LATEST ARTICLES

MUST READ

“I am because you are,” is the themed meaning behind the famed Ubuntu operating system. Moreover, this mindful phrase is practical because it continues to lure more individuals into the Ubuntu universe. Because great power beckons great responsibility, Ubuntu is stepping up. It realizes that different users will want to use the Ubuntu operating system software differently.
The Ubuntu Cinnamon Remix brings together Linux Mint's Cinnamon desktop with the Ubuntu Core. While some users are welcoming the new flavor of Ubuntu with open arms, others are scratching their heads, wondering where it fits in.

10 ways to use the Chown command with examples

Any file in a Linux system belongs to a particular owner(s) and a group. It is one of the many features that maintain security in Linux systems. For example; If a file belongs to say UserA, then UserB cannot manipulate the data depending on any additional permissions set unless the user has permission to do that.

10 Best Video Editing Software for Linux

This article is for all the Linux users out there who are looking for video editors to create their own professional videos, which can range from short documentaries to even movies.

How to install Android Studio on Ubuntu

Android Studio, like the name suggests, is a full-featured cross-platform IDE that enables you to develop Android applications to run on any android device. Based on JetBrains' IntelliJ IDEA, Android Studio comes installed with all the necessary features needed for Android development.

6 best task managers for Linux

One of the essential tools in any Linux distribution is a Task Manager. It is a system monitor application that gives you a report of all programs running on your computer and the status of your RAM and CPU usage.