Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

What is argparse usage in Python?

Ayesha Naeem

The argparse module provides a convenient interface to handle the command line arguments. It displays the generic usage of the program, help, and errors.

usage is a parameter of the ArgumentParses object. Its purpose is to display a string with information about the program and its arguments. By default, usage uses the program’s arguments to construct a usage message.

Example

The following example demonstrates how to run a program with command-line arguments using the argparse module.

The program program.py takes a single command-line argument for the radius and calculates the area of the circle. The ArgumentParser object parser is created to add arguments and parse them.

import math
import argparse

#create an ArgumentParser object
parser = argparse.ArgumentParser(description = 'Calculate radius of the circle')
#declare arguments
parser.add_argument('-r','--radius', type = int, required = True, help='radius of the circle')
args = parser.parse_args()

def area_circle(radius):
	return (math.pi*radius*radius)

def main():
	area = area_circle(args.radius)
	print(area)
main()

                       

Entering --help displays information about the program, including its arguments and usage. By default, usage is a message calculated from the argument names, as illustrated below.

>> python program.py --help
usage: program.py [-h] -r RADIUS

Calculate radius of the circle

optional arguments:
  -h, --help            show this help message and exit
  -r RADIUS, --radius RADIUS
                        radius of the circle

usage can be overridden by specifying the usage keyword argument, as shown in line 4 of the below program.

import math
import argparse

parser = argparse.ArgumentParser(description = 'Calculate radius of the circle', prog = 'My program', usage = '%(prog)s [options]')
parser.add_argument('-r','--radius', type = int, required = True, help='radius of the circle')
args = parser.parse_args()

def area_circle(radius):
	return (math.pi*radius*radius)

def main():
	area = area_circle(args.radius)
	print(area)
main()

                       

Now, the user-specified message is displayed as the usage of the program, as illustrated below.

>>python program.py --help
usage: My program [options]

Calculate radius of the circle

optional arguments:
  -h, --help            show this help message and exit
  -r RADIUS, --radius RADIUS
                        radius of the circle

RELATED TAGS

python

CONTRIBUTOR

Ayesha Naeem
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring