How to use Python's argparse library

The argparse library

In Python, the argparse library is used to deal with command-line arguments. It makes writing user-friendly command-line programs relatively simpler. It has the following three basic functions that are most commonly used:

  1. ArgumentParser(): This is used to create a parserParser is a program that takes in a string and extracts different values from it into a data structure.. It has a few optional arguments from which the ones used most commonly are:

    • description: This takes in a string which is the text displayed before the help message.

    • prog: This is used to specify the name of the program. Its default value is sys.argv[0].

    • add_help: This is used to add a -h/--help flag to the parser. Its default value is True.

    • usage: This is used to specify a string that describes the program usage. The default is automatically generated from argument parameters.

  2. add_argument(): This is used to specify different command line arguments that the program requires. It has different parameters that are discussed below in detail.

  3. parse_args(): This is used to parse all the provided arguments and store them in a variable.

Example

import argparse # import argparse

parser = argparse.ArgumentParser() # create a parser

parser.add_argument('-name', type=str) # specify the name argument

args = parser.parse_args() # parse all the arguments

if args.name: # if the user provides a name
    print("Hello,", args.name + "!")
else: # if the user does not provide a name
    print("Hello world!")

If we click the "Run" button, the following command is executed in the terminal:

python main.py -name Saad

Note: You may also try running the code with different commands to see how it behaves.

The add_argument() method

This method is generally used to specify the different arguments required by the program.

Syntax

add_argument('flag', 'optional_flag_2', [other_optional_parameters])

Optional parameters

The different optional parameters of add_argument() method that are commonly used are:

  • type: It is used to set a type for the command line argument. The program will show an error if the provided argument is of a different data type.

  • required: This takes a value of either True or False. It's used to specify if the specific argument is necessary or not.

  • help: This takes in a string and is used to add a custom help message to that argument.

  • nargs: This takes in an integer value that specifies the number of space-separated arguments that will be stored together.

  • action: This specifies the action that is taken when that argument is encountered on the command line. A possible value is 'store_true', which sets the value to True.

  • dest: This specifies the name of the attribute that is added to the parse_args() namespace.

Example

import argparse # import argparse

parser = argparse.ArgumentParser() # create a parser

# specify the argument
parser.add_argument('-name', '-n', type=str, required=True, help='Please enter the name in the format: firstName lastName', nargs=2)

args = parser.parse_args() # parse all the arguments

print("Hello! Your full name is:", args.name[0], args.name[1])

If we click the "Run" button, the following command is executed in the terminal:

python main.py -n Saad Mehmoon

Note: You may also try running the code with different commands to see how it behaves.

The add_mutually_exclusive_group() method

This function is used when we want to specify a group of arguments that is mutually exclusive from another. For example, there are two sets of arguments x and y. This method is used if we want to restrict the use of x in case the user decides to use y. It will only allow one of them at a time.

Example

import argparse # import argparse

parser = argparse.ArgumentParser() # create a parser

# make a group
group = parser.add_mutually_exclusive_group()
group.add_argument('--multiply', action='store_true')
group.add_argument('--divide', action='store_true')

# specify the arguments
parser.add_argument('x', type=int)
parser.add_argument('y', type=int)

args = parser.parse_args() # parse all the arguments

if args.multiply:
    print("The product is:", args.x*args.y)
elif args.divide:
    print("The quotient is:", args.x/args.y)

If we click the "Run" button, the following command is executed in the terminal:

python main.py --multiply 2 3

Note: You may also try running the code with --divide flag to see how it behaves.

Subparsers

Subparsers permit different sets of arguments depending on the command we run. It works in a similar fashion to mutually exclusive groups.

Example

import argparse # import argparse

parser = argparse.ArgumentParser() # create a parser
subparser = parser.add_subparsers(dest='command') # create a sub parser

login = subparser.add_parser('login')
register = subparser.add_parser('register')

# add arguments for login command
login.add_argument('--name', type=str, required=True)
login.add_argument('--password', type=str, required=True)

# add arguments for register command
register.add_argument('--name', type=str, required=True)
register.add_argument('--email', type=str, required=True)
register.add_argument('--password', type=str, required=True)
register.add_argument('--number', type=str, required=False)

args = parser.parse_args()

if args.command == 'login':
    print("Hello,", args.name + "!", "You've successfully logged in!")
elif args.command == 'register':
    print("Welcome! You account details are:")
    print(args.name)
    print(args.email)
    print(args.password)
    if args.number:
        print(args.number)

If we click the "Run" button, the following command is executed in the terminal:

python main.py register --name saadmehmoon --password hello123 --email abcd@abcd.com --number 321321321

Note: Try running the code with --login flag to see how it behaves.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved