Table of contents
1.
Introduction
2.
What is Command Line Interfaces (CLI)?
2.1.
Git
2.2.
Pip
2.3.
Bash
3.
What is argparse in Python?
4.
Argparse Module
5.
How to create CLI using Python Argparse
6.
How To Use The Created CLI
6.1.
With the default method,
6.2.
With the custom-provided method,
7.
Types of Argument in Command Line Interface(CLI)
8.
Application of Argparse in Python
9.
Benefits of argparse in Python
10.
Frequently Asked Questions
10.1.
What is argparse in Python?
10.2.
What is the difference between sys and argparse in Python?
10.3.
What is the difference between click and argparse?
11.
Conclusion
Last Updated: Nov 23, 2024
Medium

Create Command Line Argument using Python Argparse

Author Aayush Sharma
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article we will discuss the Python argparse module. This article will focus on Python argparse, its uses and how we can use it to create our own customised command-line-interfaces in python. 


There are no such prerequisites for learning python argparse. Any reader with a basic knowledge of python syntax and libraries will be able to easily understand this article and enhance his knowledge on python argparse.

Python Argparse

What is Command Line Interfaces (CLI)?

We all have seen and used command-line interfaces like GitPipBashDocker, etc., while interacting with the command line. But now the question arises, “What are command line interfaces?”.

There are two ways for a user to interact with the computer: through the graphical user interface or the command line interface. Command Line interfaces (CLI) are one of the ways to interact or tell a computer to do something using text commands entered in a terminal window.

CLIs offer various benefits over GUIs. Unlike Graphical user interface (GUI), which requires a mouse and keyboard to navigate, CLI requires the user to write commands in a predesigned syntax to perform the same result. CLIs are generally faster, more flexible, and easier to automate than GUIs. CLI commands can also be used for remote access to systems worldwide.Now we will discuss some of the most common command line interfaces.

Git

Git is a popular version control system used to maintain source code changes during software development. Git allows many users to work simultaneously on the same project without worrying about overwriting each other’s code. Git has many tools for tracking changes in a codebase, reverting to its previous version, comparing between two different versions, and many more. Some of the commands used in git are shown below.

$ git init
$ git add <filename>
$ git commit -m "Commit message"

Pip

Pip is a package manager for python used to install, upgrade and delete libraries in python. Pip allows us to download and install packages from Python Package Index (PyPI). Some examples of commands in pip are also shown below.

$ pip download <package_name>
$ pip install <package_name>
$ pip uninstall <package_name>

Bash

Bash is a Unix command language used by default on Linux and Unix-based operating systems. Bash provides the user with an interface to interact with the operating system and execute commands in the console. Some of the most common bash commands are shown below.

$ mkdir directory_nameWhat is the use of the “--verbose” flag in Python argparse?
$ rm file_name
$ cp file_name new_file_name
bash

What is argparse in Python?

The Python standard library includes a module called argparse that is used to parse command-line options and arguments. It makes the process of creating scripts that take command-line inputs easier. Developers can specify the names, types, default values, and help messages for the arguments that a script should accept using argparse. The specified command-line arguments are then automatically processed by this module to make sure they are in the correct format.
Options, subcommands, and positional arguments can all be used with argparse to handle complex argument structures. Users can also receive helpful error handling and help messages from it.

Also see, Python Operator Precedence

Argparse Module

Now we know about these command line interfaces and their usage, but what if we want to make them in python? This is where Python argparse comes in handy. Python argparse provides us with a way to create our command-line interfaces easily.

How to create CLI using Python Argparse

Python argparse provides easy-to-specify command-line arguments that are valid in scripts. Python argparse can also generate help and usage messages for user-written commands, just like popular CLIs like git. You need to follow the following steps to create CLI using Python argparse.

Step 1: Install the “argparse” module
If you have an older version of python that does not include argparse by default in the standard library, you can install it using pip.

pip install argparse

 

Step 2: Import the argparse module

import argparse

 

Step 3: Create an instance of the ArgumentParser class of the argparse module.

parser=argparse.ArgumentParser(description=’Hey Ninja! This is my custom command-line program’, usage=’%(prog)s [options]’)

 

The ArgumentParser class has several different parameters like “usage”, “description”, “epilog”, “add-help,” etc. These parameters can be used to customise the behaviour of our command line interface. The “description” parameter used above briefly describes the program to help the user understand. In contrast, the parameter “usage” gives the user a usage message when they run any command with the “help” flag.

 

Step 4: If we want to add more parameters to our parser, we can add them using the add_argument() method.

parser.add_argument(argument_default=None);
parser.add_argument(epilog=’Information displayed at the end of the help message);

 

In this step we added two more arguments. The first one is the “argument_default”  which sets the default value for all arguments. The other one is the “epilog” which shows the message that is displayed at the end of the help message.

 

Step 5: After creating and defining the instance, we parse the command line arguments. This is done with the help of the “parse_args()” method.

args=parser.parse_args()

 

The “parse_args” method will return an object containing the values of the command-line arguments set by us. Like standard objects, the values of the return object’s attributes can be accessed using the “” operator.


Below is a complete example of creating a simple CLI to welcome users using the “argparse” module in python.

# import the argparse module
import argparse

#creating the parser
parser=argparse.ArgumentParser(description=’Coding Ninjas CLI’)

#adding arguments
parser.add_argument(‘name’, help=’your name’)
parser.add_arguement(‘g’, ‘--greeting’ ,help=’Hello Ninja’)

#parsing the arguments
args=parser.parse_args()

#using the arguments
If args.greeting:
print(f”{args.greeting}, {args.name}!”)
else:
  print(f”Hello, {args.name}!”)

 

Explanation:
In the above program, we first create the “ArgumentParser” object and its full description and add the required arguments. Then we parse the arguments using the parse_args() method.
We have set the default value of the greeting as “Hello [name].” If the user provides a customised greeting, it is printed instead of the default one.

How To Use The Created CLI

We have created a simple CLI using the argparse module. Now it’s the turn to see how it works. We have shown how this CLI works in two different conditions, one with passing the greeting and one without it.

With the default method,

In this method we have simply used the CLI without passing any argument.

Code:

$ python greet.py Ninja

 

Output:

Hello, Ninja!

 

Explanation:
In this case we have called the command without giving any greeting. Hence the default argument gets called and we see the above output.

With the custom-provided method,

In this method we provide the CLI a “Long time no see” custom greeting.

Code:

$ python greet.py Ninja -g “Long time no see”

 

Output:

Long time no see Ninja!

 

Explanation:
In this case the user has provided a customised greeting with the command. Therefore the above output is shown with the provided greeting.

Check out this article - Swapcase in Python, and  Convert String to List Python

Also see, How to Check Python Version in CMD

Types of Argument in Command Line Interface(CLI)

In a Command Line Interface (CLI), there are generally three types of arguments:

  • Positional Arguments: These are required arguments specified in a specific order. They don't have flags or names associated with them. For example, in a command like python script.py arg1 arg2, arg1 and arg2 are positional arguments
     
  • Optional Arguments (Flags): These are arguments that are not mandatory. They are specified with flags or names and have default values if not provided. They are typically preceded by a hyphen or double hyphen. For example, in a command like python script.py --option1 value1 --option2 value2, --option1 and --option2 are optional arguments
     
  • Sub-commands: These are like separate commands within a main command. Each sub-command can have its own set of arguments. For example, in a command like git commit -m "message", commit is a sub-command

Application of Argparse in Python

  1. Handling Command-Line Arguments: argparse simplifies the process of retrieving input from the command line. It allows developers to specify required and optional arguments and ensures they are correctly parsed. Example: Creating a script that accepts filenames or specific parameters to perform operations.
  2. Input Validation: It can enforce types and constraints on the input arguments. For example, ensuring that a provided number is an integer or falls within a specific range.
  3. Building Flexible and Modular Scripts: Allows for defining multiple arguments and subcommands for modular functionality. For instance, a script with add, delete, and update subcommands for managing data.
  4. User-Friendly Help and Documentation: Automatically generates help messages based on the arguments and their descriptions, making the script more accessible to end users.
  5. Default Values and Argument Configuration: Provides default values for arguments if none are supplied by the user. Example: A timeout argument defaulting to 30 seconds if the user doesn't specify it.
  6. Combining Positional and Optional Arguments: Supports both positional arguments (e.g., required filenames) and optional arguments (e.g., flags or settings).
  7. Creating Reusable Tools and Automation Scripts: Command-line tools created using argparse can be integrated into larger systems or reused as utilities.

Benefits of argparse in Python

The argparse module in Python offers several benefits:

  • User-Friendly Command Line Interfaces: It provides a structured and intuitive way for users to interact with command-line programs, making them more accessible
     
  • Argument Validation: argparse automatically handles argument validation, ensuring that provided inputs meet specified criteria (e.g., correct data types)
     
  • Help Messages: It generates informative help messages, displaying the available arguments, their usage, and descriptions. This aids users in understanding how to use the program
     
  • Handling of Complex Argument Structures: It supports various argument types, including positional arguments, optional arguments, and sub-commands, allowing for flexible and sophisticated command-line interfaces

Frequently Asked Questions

What is argparse in Python?

argparse is a Python module for creating command-line interfaces, allowing developers to define, parse, and validate command-line arguments and options easily.

What is the difference between sys and argparse in Python?

sys provides raw access to command-line arguments, while argparse simplifies argument parsing with validation, help messages, and structured interface creation.

What is the difference between click and argparse?

click is a third-party library for building complex, user-friendly CLI tools with decorators, while argparse is a simpler, built-in module for basic argument parsing.

Conclusion

We hope this article was insightful and helped you in learning something new. This article discussed the Python argparse module in python and its uses. Then we discussed how to build customised CLI using python argparse with examples. In the end, we concluded by giving examples of how to use our newly created command line interface.If you want to learn more, you can refer to these articles:

Do visit our website to read more such blogs. Refer to our Guided Path on Code360 to upskill yourself! You can check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! If you are looking for questions asked by tech giants, in that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

Live masterclass