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.
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")
Customization
Custom Usage help
parser = argparse.ArgumentParser(description = "Path Existence Checker", usage="cla.py path")
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.
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.
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:
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.