The Wayback Machine - https://web.archive.org/web/20240922155305/https://www.geeksforgeeks.org/command-line-option-and-argument-parsing-using-argparse-in-python/
Open In App

Command-Line Option and Argument Parsing using argparse in Python

Last Updated : 14 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Command line arguments are those values that are passed during the calling of the program along with the calling statement. Usually, python uses sys.argv array to deal with such arguments but here we describe how it can be made more resourceful and user-friendly by employing argparse module.

Python Argparse Module

The ‘argparse' module in Python helps create a program in a command-line-environment in a way that appears not only easy to code but also improves interaction. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.

Steps for Using Argparse

Creating a Parser: Importing argparse module is the first way of dealing with the concept. After you’ve imported it you have to create a parser or an ArgumentParser object that will store all the necessary information that has to be passed from the python command-line.

Syntax: class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars=’-‘, fromfile_prefix_chars=None, argument_default=None, conflict_handler=’error’, add_help=True, allow_abbrev=True) Parameters:
  • prog– name of the program (default=sys.argv[0])
  • usage– string describes the program usage(default: generated from arguments added to the parser)
  • description– text to display before the argument help(default: none)
  • epilog– text to display after the argument help (default: none)
  • parents– list of ArgumentParser objects whose arguments should also be included
  • formatter_class– class for customizing the help output
  • prefix_chars– set of characters that prefix optional arguments (default: ‘-‘)
  • fromfile_prefix_chars– set of characters that prefix files from which additional arguments should be read (default: None)
  • argument_default– global default value for arguments (default: None)
  • conflict_handler– strategy for resolving conflicting optionals (usually unnecessary)
  • add_help– Add a -h/–help option to the parser (default: True)
  • allow_abbrev– Allows long options to be abbreviated if the abbreviation is unambiguous. (default: True)


Adding Arguments: Next step is to fill the ArgumentParser with the information about the arguments of the program. This implies a call to the add_argument() method. These information tell ArgumentParser how to take arguments from the command-line and turn them into objects.

Syntax: ArgumentParser.add_argument(name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest]) Parameters:
  • name or flags– either a name or list of option string
  • action– basic type of action to be taken when this argument is encountered at the command line
  • nargs– number of command-line arguments that should be consumed
  • const– constant value required by some action and nargs selections
  • default– value produced if the arguments are absent from the command line
  • type– type to which the command line arguments should be converted.
  • choices – A container of the allowable values for the argument
  • required – Whether or not the command-line option may be omitted (optionals only)
  • help– brief description of what the argument does
  • metavar – A name for the argument in usage messages
  • dest – The name of the attribute to be added to the object returned by parse_args()


Parsing Arguments: The information gathered in the step 2 is stored and used when arguments are parsed through parse_args(). The data is initially stored in sys.argv array in a string format. Calling parse_args() with the command-line data first converts them into the required data type and then invokes the appropriate action to produce a result.

Syntax: ArgumentParser.parse_args(args=None, namespace=None) Parameter:
  • args – List of strings to parse. The default is taken from sys.argv.
  • namespace – An object to take the attributes. The default is a new empty Namespace object


Application of Argparse in Python

In most cases, this means a simple Namespace object will be built up from attributes parsed out of the command line:

Namespace(accumulate=, integers=[ 2, 8, -7, 41 ])


These were the root concepts you need to be familiar with to deal with argparse. The following are some examples to support this application.

Example 1: To find the sum of command-line arguments using argparse

This code employs the ‘argparse' module to create a command-line interface for processing integers. It defines two command-line arguments: ‘integers’ to accept multiple integer values, and ‘accumulate’ to perform a sum operation on those integers. When the script is executed with integer values as arguments, it parses and calculates the sum of those integers, displaying the result. It provides a convenient way to perform integer accumulation through the command line.

Python
import argparse
parser = argparse.ArgumentParser(description ='Process some integers.')
parser.add_argument('integers', metavar ='N', 
                    type = int, nargs ='+',
                    help ='an integer for the accumulator')

parser.add_argument(dest ='accumulate', 
                    action ='store_const',
                    const = sum, 
                    help ='sum the integers')

args = parser.parse_args()
print(args.accumulate(args.integers))

Output:

python-argparse

Example 2: Program to arrange the integer inputs in ascending order

This code utilizes the ‘argparse' module to create a command-line interface for sorting integers in ascending order. It defines two command-line arguments: ‘integers’ to accept multiple integer values and ‘accumulate’ to arrange these integers using the ‘sorted' function. When the script is executed with integer values as arguments, it parses and displays the sorted integers in ascending order, offering a convenient way to perform integer sorting through the command line.

Python
import argparse
parser = argparse.ArgumentParser(description ='sort some integers.')
parser.add_argument('integers',
                    metavar ='N',
                    type = int,
                    nargs ='+',
                    help ='an integer for the accumulator')

parser.add_argument(dest ='accumulate',
                    action ='store_const',
                    const = sorted,
                    help ='arranges the integers in ascending order')

args = parser.parse_args()
print(args.accumulate(args.integers))

Output:

python-argparse

Example 3: To find the average of the entered command line numerical arguments

This code utilizes the ‘argparse' module to create a command-line interface for calculating the average of floating-point numbers. It defines two command-line arguments: ‘integers’ to accept multiple floating-point values and ‘sum’ and ‘len’ to perform sum and length calculations. The script calculates the average by dividing the sum by the number of provided values and prints the result. It offers a straightforward way to compute the average of floating-point numbers through the command line.

Python
import argparse
parser = argparse.ArgumentParser(description ='sort some integers.')
parser.add_argument('integers',
                    metavar ='N',
                    type = float,
                    nargs ='+',
                    help ='an integer for the accumulator')

parser.add_argument('sum',
                    action ='store_const',
                    const = sum)

parser.add_argument('len',
                    action ='store_const',
                    const = len)

args = parser.parse_args()
add = args.sum(args.integers)
length = args.len(args.integers)
average = add / length
print(average)

Output:

python-argparse

Command-Line Option and Argument Parsing using argparse in Python – FAQs

How to Build Command-Line Interfaces in Python with argparse

argparse is a powerful module in Python for building command-line interfaces. It makes it easy to write user-friendly command-line interfaces, and the program defines what arguments it requires, and argparse figures out how to parse those out of sys.argv. Here’s a basic example to get you started:

import argparse

def main():
# Create the parser
parser = argparse.ArgumentParser(description="Example CLI using argparse")

# Add an argument
parser.add_argument('number', type=int, help="An integer number")

# Parse the arguments
args = parser.parse_args()

# Use the argument
print(f"The number you entered is {args.number}")

if __name__ == "__main__":
main()

In this example, when you run this script from the command line and pass an integer, it prints the integer with a message.

How Do You Fetch Command Line Arguments in Python?

Command-line arguments in Python can be fetched using the sys.argv list from the sys module, where sys.argv[0] is the script name and sys.argv[1] onwards are the arguments. However, using argparse provides a more sophisticated way to handle command-line arguments:

import sys

# Fetching command-line arguments directly
print(sys.argv)

# Typically, you would want to process or validate these arguments before using them.

How to Pass Command-Line Arguments in Python argparse

To pass command-line arguments in Python using argparse, you define the arguments you expect in the script using add_argument() method and then parse them using parse_args(). Each argument can be specified as either positional or optional:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
args = parser.parse_args()
print(args.echo)

What Are Optional Arguments in Command Line?

Optional arguments are those that can be omitted at runtime. They often provide additional controls or modifiers that affect the program’s behavior. In argparse, optional arguments are typically prefixed with - or -- and can be distinguished because they do not need to be present for the script to run:

parser.add_argument("-v", "--verbose", help="increase output verbosity",
action="store_true")

Here, -v or --verbose is optional, and if provided, it changes the verbosity level of the output.

What is the Difference Between Options and Arguments in Command-Line?

  • Arguments are usually positional and mandatory data that the command needs to operate, such as filenames or data.
  • Options are additional modifiers that dictate or alter the behavior of the command but are usually optional. Options can have additional associated values (e.g., -o output.txt).

For example, in the command cp file1.txt file2.txt, file1.txt and file2.txt are arguments. However, in ls -l /home, -l is an option that modifies how the list is displayed, and /home is an argument specifying the directory.

argparse in Python abstracts these concepts to allow easy command-line parsing, providing clear distinctions and handling for both arguments and options to build sophisticated command-line interfaces



Similar Reads

Argparse VS Docopt VS Click - Comparing Python Command-Line Parsing Libraries
Before knowing about the Python parsing libraries we must have prior knowledge about Command Line User Interface. A Command Line Interface (CLI) provides a user-friendly interface for the Command-line programs, which is most commonly favored by the developers or the programmers who prefer keyboard programming, instead of using the mouse. By buildin
4 min read
How to pass a list as a command-line argument with argparse?
Argparse is a Python library used to parse command-line arguments in a user-friendly manner. It makes it easy to write user-friendly command-line interfaces, and it is widely used in Python applications. In this tutorial, we will discuss how to pass a list as a command-line argument using the Argparse library in Python. Passing a List as a Command
5 min read
How to Fix: SyntaxError: positional argument follows keyword argument in Python
In this article, we will discuss how to fix the syntax error that is positional argument follows keyword argument in Python An argument is a value provided to a function when you call that function. For example, look at the below program - Python Code # function def calculate_square(num): return num * num # call the function result = calculate_squa
3 min read
Pass list as command line argument in Python
The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. One of them is sys module. sys Module A module is a file containing Python definitions and statements. The sys module provides functi
3 min read
Python: Key Value pair using argparse
The argparse module in Python helps create a program in a command-line-environment in a way that appears not only easy to code but also improves interaction. It also automatically generates help and usage messages and issues errors when users give the program invalid arguments. Steps For Using Argparse Module: Creating a Parser: Importing argparse
2 min read
How to handle invalid arguments with argparse in Python?
Argparse module provides facilities to improve the command-line interface. The methods associated with this module makes it easy to code for command-line interface programs as well as the interaction better. This module automatically generates help messages and raises an error when inappropriate arguments are passed. It even allows customizing the
4 min read
How to parse boolean values with `argparse` in Python
Command-line arguments are a powerful feature of many programming languages, including Python. They allow developers to specify options or parameters when running a script, making it more flexible and customizable. However, the process of parsing these arguments can be a tedious and error-prone task if done manually. The 'argparse' module in Python
5 min read
Argparse: Way to include default values in '--help'?
Argparse in Python allows you to create user-friendly command-line interfaces. By including default values in the --help output, you can make your script's behavior more transparent. There are several ways to achieve this, including using argparse.ArgumentDefaultsHelpFormatter and custom help formatters. Include default values in '--help'Below are
2 min read
Parsing and Processing URL using Python - Regex
Prerequisite: Regular Expression in Python URL or Uniform Resource Locator consists of many information parts, such as the domain name, path, port number etc. Any URL can be processed and parsed using Regular Expression. So for using Regular Expression we have to use re library in Python. Example: URL: https://www.geeksforgeeks.org/courses When we
3 min read
Parsing and converting HTML documents to XML format using Python
In this article, we are going to see how to parse and convert HTML documents to XML format using Python. It can be done in these ways: Using Ixml module.Using Beautifulsoup module.Method 1: Using the Python lxml library In this approach, we will use Python's lxml library to parse the HTML document and write it to an encoded string representation of
3 min read
Return the Angle of the Complex Argument in Radians in Python using NumPy
In this article, we are going to see how to return the angle of the complex argument in radians in Python Using NumPy. The NumPy library provides the numpy.angle() method to return the angle of the complex argument in radians in python. Let's look at the syntax of the method. Syntax: numpy.angle(z, deg=False) parameters: z: array like object. input
3 min read
Least Astonishment and the Mutable Default Argument in Python
The principle of Least Astonishment (also known as least surprise) is a design guideline that states that a system should behave the way it is intended to behave. It should not change its behavior in an unexpected manner to astonish the user. By following this principle, designers can help to create user interfaces that are more user-friendly and l
3 min read
Keyword and Positional Argument in Python
Python provides different ways of passing the arguments during the function call from which we will explore keyword-only argument means passing the argument by using the parameter names during the function call. Types of argumentsKeyword-only argumentPositional-only argumentDifference between the Keyword and Positional ArgumentKeyword-Only Argument
4 min read
Parsing XML with DOM APIs in Python
The Document Object Model (DOM) is a programming interface for HTML and XML(Extensible markup language) documents. It defines the logical structure of documents and the way a document is accessed and manipulated. Parsing XML with DOM APIs in python is pretty simple. For the purpose of example we will create a sample XML document (sample.xml) as bel
2 min read
Parsing PDFs in Python with Tika
Apache Tika is a library that is used for document type detection and content extraction from various file formats. Using this, one can develop a universal type detector and content extractor to extract both structured text and metadata from different types of documents such as spreadsheets, text documents, images, PDF's, and even multimedia input
2 min read
Parsing DateTime strings containing microseconds in Python
Most of the applications require a precision of up to seconds but there are also some critical applications that require nanosecond precision, especially the ones which can perform extremely fast computations. It can help provide insights on certain factors related to time space for the application. Let us see how can we parse DateTime strings that
3 min read
JSON Parsing Errors in Python
JSON is a widely used format for exchanging data between systems and applications. Python provides built-in support for working with JSON data through its JSON module. However, JSON parsing errors can occur due to various reasons such as incorrect formatting, missing data, or data type mismatches. There are different JSON parsing errors that can oc
6 min read
XML parsing in Python
This article focuses on how one can parse a given XML file and extract some useful data out of it in a structured way. XML: XML stands for eXtensible Markup Language. It was designed to store and transport data. It was designed to be both human- and machine-readable.That's why, the design goals of XML emphasize simplicity, generality, and usability
7 min read
How to pass argument to an Exception in Python?
There might arise a situation where there is a need for additional information from an exception raised by Python. Python has two types of exceptions namely, Built-In Exceptions and User-Defined Exceptions.Why use Argument in Exceptions? Using arguments for Exceptions in Python is useful for the following reasons: It can be used to gain additional
2 min read
Python Lambda with underscore as an argument
In Python, we use the lambda keyword to declare an anonymous function. Lambda function behaves in the same way as regular functions behave that are declared using the 'def' keyword. The following are some of the characteristics of Python lambda functions: A lambda function can take more than one number of arguments, but they contain only a single e
1 min read
Use mutable default value as an argument in Python
Python lets you set default values ​​for its parameters when you define a function or method. If no argument for this parameter is passed to the function while calling it in such situations default value will be used. If the default values ​​are mutable or modifiable (lists, dictionaries, etc.), they can be modified within the function and those mo
5 min read
Specify Argument Type For List of Dictionary For a Python
In this article, we will see how we can specify the argument type for a list of Dictionary for Python. As we know, Python is a dynamically typed language so the data type of a variable can change anytime. If a variable containing an integer may hold a string in the future, which can lead to Runtime Errors, Therefore knowing the data type of the arg
2 min read
Variable Length Argument in Python
In this article, we will cover about Variable Length Arguments in Python. Variable-length arguments refer to a feature that allows a function to accept a variable number of arguments in Python. It is also known as the argument that can also accept an unlimited amount of data as input inside the function. There are two types in Python: Non - Keyword
4 min read
Why Python Uses 'Self' as Default Argument
Python, a versatile and widely used programming language, follows object-oriented principles in its design. One of the distinctive features of Python is the use of the keyword 'self' as a default argument in class methods. This choice plays a crucial role in maintaining the integrity of object-oriented programming (OOP) concepts and ensures proper
3 min read
How to Fix TypeError: String Argument Without an Encoding in Python
The TypeError: string argument without an encoding is a common error that arises when working with the string encoding in Python. This error typically occurs when attempting to the convert a string to the bytes without specifying the necessary encoding. In this article, we will explore the causes of this error and provide the practical solutions to
3 min read
How to fix Python Multiple Inheritance generates "TypeError: got multiple values for keyword argument".
Multiple inheritance in Python allows a class to inherit from more than one parent class. This feature provides flexibility but can sometimes lead to complications, such as the error: "TypeError: got multiple values for keyword argument". This error occurs when the method resolution order (MRO) leads to ambiguous function calls, especially with key
5 min read
Passing function as an argument in Python
A function can take multiple arguments, these arguments can be objects, variables(of same or different data types) and functions. Python functions are first class objects. In the example below, a function is assigned to a variable. This assignment doesn’t call the function. It takes the function object referenced by shout and creates a second name
5 min read
Python | Set 6 (Command Line and Variable Arguments)
Previous Python Articles (Set 1 | Set 2 | Set 3 | Set 4 | Set 5) This article is focused on command line arguments as well as variable arguments (args and kwargs) for the functions in python. Command Line Arguments Till now, we have taken input in python using raw_input() or input() [for integers]. There is another method that uses command line arg
2 min read
Parsing tables and XML with BeautifulSoup
Scraping is a very essential skill that everybody should learn, It helps us to scrap data from a website or a file that can be used in another beautiful manner by the programmer. In this article, we will learn how to extract tables with beautiful soup and XML from a file. Here, we will scrap data using the Beautiful Soup Python Module. Perquisites:
4 min read
Command Line Scripts | Python Packaging
How do we execute any script in Python? $ python do_something.py $ python do_something_with_args.py gfg vibhu Probably that's how you do it. If your answer was that you just click a button on your IDE to execute your Python code, just assume you were asked specifically how you do it on command line. Let's make it easier for you. $ do_something $ do
4 min read
Article Tags :
Practice Tags :