Updated On : Jan-15,2021 Time Investment : ~20 mins

argparse - Simple Guide to Command-Line Arguments Handling in Python

When we run a python script from the shell/command prompt, it’s quite common to give arguments to the script. We generally keep parameters that we require dynamically as arguments given to the script so that we can supply those arguments when we run the script. The arguments that we pass to the python script are available to us in the program as a list of strings through sys.argv. We can write our code which parses arguments given to the script from sys.argv, but it gets tricky to handle if our script has many arguments and many of them are optional. Python has a module named argparse which can make our task of handling command-line arguments easy. It provides a very easy to use interface with lots of functionalities to handle command-line arguments efficiently. Apart from efficiently handling arguments, argparse also provides useful help and usage messages which can guide a person about how to use parameters. It even gives an error when the program is given unexpected values as an argument or some of the compulsory arguments are missing. The argparse will parse arguments from sys.argv itself for us. As a part of this tutorial, we'll try to explain with simple examples how we can use the argparse module to parse command-line arguments. We'll try to cover as much of the API of the module as possible to give more exposure.

Steps to Create Argument Parser

The process of creating an argument parser using argparse requires to follow a list of simple steps:

  • Create ArgumentParser() parser instance.
  • Add arguments to parser by calling add_argument() methods. We need to call this method for each individual argument hence there can be multiple calls to it.
  • Call parse_args() method on parser instance. It'll return Namespace instance. Namespace is a dictionary-like instance that let us access individual arguments by the name. The name of an argument is defined when we called add_argument() method in the previous step.

We'll now explain with simple examples how we can create an argument parser and handle arguments of different types.

Example 1: Simple Argument Parser

Our first example explains the creation of a simple parser that does not add any arguments. We have just created parser using ArgumentParser() and parsed arguments using parse_args(). We have then printed the output of parsed arguments. This example is to demonstrate that even though we have not added any argument to the parser, we get a simple help message by default. It's created and formatted by the parser itself.

argparse_example_1.py
import argparse

arg_parser = argparse.ArgumentParser()

args = arg_parser.parse_args()

print(args)

Below we have shown how we called our script in a different way and printed what output we got after running them. We can see that when we just simply run the script without any argument it prints Namespace instance which does not seem to have any arguments. We'll be printing namespace instances in all our examples to demonstrate how and what values are stored in them.

We have then called our script with --help and -h arguments to print help message generated by default. Argparse takes script name from sys.argv[0] and prints in help if we have explicitly not provided program name when creating ArgumentParser instance. The help message's first line explains how we can use this program and the remaining lines explain compulsory and optional parameters.

ArgumentParser() has a boolean parameter named add_help which is responsible for adding help doc. It's set to True by default hence help text is created by default.


  • python argparse_example_1.py

    OUTPUT

Namespace()

  • python argparse_example_1.py --help

    OUTPUT

usage: argparse_example_1.py [-h]

optional arguments:
  -h, --help  show this help message and exit

  • python argparse_example_1.py -h

    OUTPUT

usage: argparse_example_1.py [-h]

optional arguments:
  -h, --help  show this help message and exit

NOTE: Please make a note that as we add arguments to the parser, the parser will keep on updating help message with information about those arguments without we needing to explicitly take any step.

Example 2: Compulsory Arguments

As a part of our second example, we'll demonstrate how we can introduce compulsory arguments for the program. The program will fail to run without these arguments. We have created a simple script below which creates two compulsory arguments using add_argument() method. We need to pass the parameter name as the first argument. We have then parsed these arguments and printed the result (Namespace instance). Namespace is a dictionary-like object which will hold all parameters and their values. We have also introduced a new argument named help in the add_argument() method which can have a help string that will be displayed for the parameter when we print help.

argparse_example_2.py
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("param1", help="First  Number for Operation")
parser.add_argument("param2", help="Second Number for Operation")

args = parser.parse_args()

print(args)

Below we have executed the script in a different way and printed the output of each run. We can see from the output that if we don't provide the script with 2 arguments then it'll fail. When we provide two needed arguments, the script runs successfully and we can see Namespace with parameter values. We can see that Namespace has an entry for each parameter with its name as key and input value as value. Please make a note that when we ran the script with the help parameter, we can see the help message printed which we provided for parameters.


  • python argparse_example_2.py

    OUTPUT

usage: argparse_example_2.py [-h] param1 param2
argparse_example_2.py: error: the following arguments are required: param1, param2

  • python argparse_example_2.py --help

    OUTPUT

usage: argparse_example_2.py [-h] param1 param2

positional arguments:
  param1      First Number for Operation
  param2      Second Number for Operation

optional arguments:
  -h, --help  show this help message and exit

  • python argparse_example_2.py 123

    OUTPUT

usage: argparse_example_2.py [-h] param1 param2
argparse_example_2.py: error: the following arguments are required: param2

  • python argparse_example_2.py 123 456

    OUTPUT

Namespace(param1='123', param2='456')

  • python argparse_example_2.py 3 3 3

    OUTPUT

usage: argparse_example_2.py [-h] param1 param2
argparse_example_2.py: error: unrecognized arguments: 3

Example 3: Operations With Parsed Arguments

As a part of our third example, we'll explain how we can access values from the Namespace instance. Our script for this part is almost the same as the previous example with the addition of code that accesses arguments from Namespace instance and prints their type and values. We are also adding values of both arguments at last and printing them.

argparse_example_3.py
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("param1", help="First  Number for Operation")
parser.add_argument("param2", help="Second Number for Operation")

args = parser.parse_args()

print(args)

print("\nParam 1 : Type = %s, Value = %s"%(type(args.param1), args.param1))
print("Param 2 : Type = %s, Value = %s"%(type(args.param2), args.param2))

print("\nAddition of Param1 & Param2 = ", args.param1 + args.param2)

We can notice from the below output that both the arguments are of type string and when we add them, it does not result in output that we expect though the script ran successfully.

Please make a note that until we explicitly specify the data type of arguments, it'll be considered a string by default.


  • python argparse_example_3.py 123 456

    OUTPUT

Namespace(param1='123', param2='456')

Param 1 : Type = <class 'str'>, Value = 123
Param 2 : Type = <class 'str'>, Value = 456

Addition of Param1 & Param2 =  123456

Example 4: Enforcing Data Types On Arguments

As a part of our fourth example, we'll build on the last example and add data types to arguments. Our script for this example is exactly the same as the previous example with only one change which is the introduction of type parameter in add_argument() method. We have introduced an integer data-type for both parameters. This will enforce the user to provide integer values for both arguments.

argparse_example_4.py
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("param1", help="First  Number for Operation", type=int)
parser.add_argument("param2", help="Second Number for Operation", type=int)

args = parser.parse_args()

print(args)

print("\nParam 1 : Type = %s, Value = %s"%(type(args.param1), args.param1))
print("Param 2 : Type = %s, Value = %s"%(type(args.param2), args.param2))

print("\nAddition of Param1 & Param2 = ", args.param1 + args.param2)

We have executed the script in different ways to verify that the data type is enforced or not. We can see from the first output that the script now gives the output that we expect. From the second output, we can notice that it does not accept string values as input.


  • python argparse_example_4.py 123 456

    OUTPUT

Namespace(param1=123, param2=456)

Param 1 : Type = <class 'int'>, Value = 123
Param 2 : Type = <class 'int'>, Value = 456

Addition of Param1 & Param2 =  579

  • python argparse_example_4.py 12 abc

    OUTPUT

usage: argparse_example_4.py [-h] param1 param2
argparse_example_4.py: error: argument param2: invalid int value: 'abc'

Example 5: Optional Arguments

As a part of our fifth example, we'll explain how we can introduce optional arguments. We can add options arguments by giving argument name which starts with a single dash (-) or double dash (--) in the add_argument() method. The argument whose name starts with these values will be considered optional and won't be required to run the script.

Our script of this example builds on the script from the last example. We have added one optional parameter named --power-to which accepts integer values. We have introduced the condition that when this parameter is provided we raise the addition of first to parameters to the power of the value of this optional parameter. If this optional parameter is not provided then we simply add two numbers.

argparse_example_5.py
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("param1", help="First  Number for Operation", type=int)
parser.add_argument("param2", help="Second Number for Operation", type=int)
parser.add_argument("--power-to", help="Raise Addition of Parameters to the Power", type=int)

args = parser.parse_args()

print(args)

print("\nParam 1 : Type = %s, Value = %s"%(type(args.param1), args.param1))
print("Param 2 : Type = %s, Value = %s"%(type(args.param2), args.param2))

if args.power_to:
    res = (args.param1 + args.param2)**args.power_to
    print("\nAddition of Param1 (%d) & Param2 (%d) Raised to %d = %d"%(args.param1, args.param2, args.power_to, res))
else:
    print("\nAddition of Param1 & Param2 = ", args.param1 + args.param2)

We have executed the script below in different ways. We can notice from the runs that argparse lets us include optional arguments as well as it lets us provide arguments in any sequence and it'll still work. This reduces a lot of code that we might need to write if manually handle argument using sys.argv. We have also printed a help message to check the presence of an optional argument in it.

We recommend that the developer keep an eye on Namespace instance as it gives out useful information for debugging purposes if we face any issues.


  • python argparse_example_5.py 4 5

    OUTPUT

Namespace(param1=4, param2=5, power_to=None)

Param 1 : Type = <class 'int'>, Value = 4
Param 2 : Type = <class 'int'>, Value = 5

Addition of Param1 & Param2 =  9

  • python argparse_example_5.py 2 3 --power-to 2

    OUTPUT

Namespace(param1=2, param2=3, power_to=2)

Param 1 : Type = <class 'int'>, Value = 2
Param 2 : Type = <class 'int'>, Value = 3

Addition of Param1 (2) & Param2 (3) Raised to 2 = 25

  • python argparse_example_5.py --power-to 2 3 3

    OUTPUT

Namespace(param1=3, param2=3, power_to=2)

Param 1 : Type = <class 'int'>, Value = 3
Param 2 : Type = <class 'int'>, Value = 3

Addition of Param1 (3) & Param2 (3) Raised to 2 = 36

  • python argparse_example_5.py 4 --power-to 2 3

    OUTPUT

Namespace(param1=4, param2=3, power_to=2)

Param 1 : Type = <class 'int'>, Value = 4
Param 2 : Type = <class 'int'>, Value = 3

Addition of Param1 (4) & Param2 (3) Raised to 2 = 49

  • python argparse_example_5.py -h

    OUTPUT

usage: argparse_example_5.py [-h] [--power-to POWER_TO] param1 param2

positional arguments:
  param1               First Number for Operation
  param2               Second Number for Operation

optional arguments:
  -h, --help           show this help message and exit
  --power-to POWER_TO  Raise Addition of Parameters to the Power

Example 6: Optional Arguments With Action

As a part of our sixth example, we'll explain usage of action parameter of add_argument() method. The action parameter takes a string value specifying the action that should be taken when the user has provided this parameter in the command line. Argparse has a list of predefined actions already which we can invoke by giving their name to the action parameter. We can create custom action by extending Action class of argparse.

Below we have given a list of few actions.

  • store - This action stores value given after parameter.
  • store_const - This action stores value specified in const argument of add_argument() method as parameter value.
  • store_true - This action stores boolean flag True as parameter value.
  • store_false - This action stores boolean flag False as parameter value.
  • append - This action lets us call parameters more than once and all values will be maintained as a list.
  • append_const - This action works like the previous action but with the difference that value specified in const parameter of add_argument() method will be maintained as a list as many times as parameter is provided.
  • count - This action will simply count how many times the parameter is provided in the command line and store count in the parameter value.

The script of this example also builds on previous examples with few additions. We have added four optional parameters --multiply, --divide, subtract and --power to our script. This parameter performs the action as per their name on two compulsory parameters. All of them has action specified as store_true. This action will set the parameter value to True whenever this parameter is provided from the command line.

argparse_example_6.py
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("param1", help="First  Number for Operation", type=int)
parser.add_argument("param2", help="Second Number for Operation", type=int)
parser.add_argument("-m", "--multiply", help="Multiply Numbers", action="store_true")
parser.add_argument("-d","--divide", help="Divide Numbers", action="store_true")
parser.add_argument("-s", "--subtract", help="Subtract Numbers", action="store_true")
parser.add_argument("-p", "--power", help="Raise First Parameter To Power of Second Parameter", action="store_true")

args = parser.parse_args()

print(args)

print("\nParam 1 : Type = %s, Value = %s"%(type(args.param1), args.param1))
print("Param 2 : Type = %s, Value = %s"%(type(args.param2), args.param2))

if args.multiply:
    print("\nMultiplication of Param1 & Param2 = ", args.param1 * args.param2)
elif args.divide:
    print("\nDivision of Param1 & Param2 = ", args.param1 / args.param2)
elif args.subtract:
    print("\nSubtraction of Param1 & Param2 = ", args.param1 - args.param2)
elif args.power:
    print("\nPower of Param1 to Param2 = ", args.param1 ** args.param2)
else:
    print("\nAddition of Param1 & Param2 = ", args.param1 + args.param2)

We have now run the script with different parameter settings. We have also printed a help message for the program. We can notice that the script seems to be working fine with different parameter settings.


  • python argparse_example_6.py -h

    OUTPUT

usage: argparse_example_6.py [-h] [-m] [-d] [-s] [-p] param1 param2

positional arguments:
  param1          First Number for Operation
  param2          Second Number for Operation

optional arguments:
  -h, --help      show this help message and exit
  -m, --multiply  Multiply Numbers
  -d, --divide    Divide Numbers
  -s, --subtract  Subtract Numbers
  -p, --power     Raise First Parameter To Power of Second Parameter

  • python argparse_example_6.py 2 3 -m

    OUTPUT

Namespace(divide=False, multiply=True, param1=2, param2=3, power=False, subtract=False)

Param 1 : Type = <class 'int'>, Value = 2
Param 2 : Type = <class 'int'>, Value = 3

Multiplication of Param1 & Param2 =  6

  • python argparse_example_6.py 2 3 -d

    OUTPUT

Namespace(divide=True, multiply=False, param1=2, param2=3, power=False, subtract=False)

Param 1 : Type = <class 'int'>, Value = 2
Param 2 : Type = <class 'int'>, Value = 3

Division of Param1 & Param2 =  0.6666666666666666

  • python argparse_example_6.py 2 3 -s

    OUTPUT

Namespace(divide=False, multiply=False, param1=2, param2=3, power=False, subtract=True)

Param 1 : Type = <class 'int'>, Value = 2
Param 2 : Type = <class 'int'>, Value = 3

Subtraction of Param1 & Param2 =  -1

  • python argparse_example_6.py 2 3 -p

    OUTPUT

Namespace(divide=False, multiply=False, param1=2, param2=3, power=True, subtract=False)

Param 1 : Type = <class 'int'>, Value = 2
Param 2 : Type = <class 'int'>, Value = 3

Power of Param1 to Param2 =  8

  • python argparse_example_6.py 2 3

    OUTPUT

Namespace(divide=False, multiply=False, param1=2, param2=3, power=False, subtract=False)

Param 1 : Type = <class 'int'>, Value = 2
Param 2 : Type = <class 'int'>, Value = 3

Addition of Param1 & Param2 =  5

Example 7: Arguments With Choices

As a part of our seventh example, we have explained how we can enforce parameters to provide value from a list of possible values by using choices parameter of add_argument() method. The script of this example is exactly the same as the fifth example with the only change that we have introduced choices parameter in method add_argument(). We have set the value of the choices parameter to a list of integer values ranging from 2-10. This will force us to provide values in this range for the parameter --power-to.

argparse_example_7.py
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("param1", help="First  Number for Operation", type=int)
parser.add_argument("param2", help="Second Number for Operation", type=int)
parser.add_argument("-p", "--power-to", help="Raise Addition of Parameters to the Power", type=int,
                    choices=[2,3,4,5,6,7,8,9,10])

args = parser.parse_args()

print(args)

print("\nParam 1 : Type = %s, Value = %s"%(type(args.param1), args.param1))
print("Param 2 : Type = %s, Value = %s"%(type(args.param2), args.param2))

if args.power_to:
    res = (args.param1 + args.param2)**args.power_to
    print("\nAddition of Param1 (%d) & Param2 (%d) Raised to %d = %d"%(args.param1, args.param2, args.power_to, res))
else:
    print("\nAddition of Param1 & Param2 = ", args.param1 + args.param2)

Below we have executed the script in a different way and printed results as well.


  • python argparse_example_7.py -h

    OUTPUT

usage: argparse_example_7.py [-h] [-p {2,3,4,5,6,7,8,9,10}] param1 param2

positional arguments:
  param1                First Number for Operation
  param2                Second Number for Operation

optional arguments:
  -h, --help            show this help message and exit
  -p {2,3,4,5,6,7,8,9,10}, --power-to {2,3,4,5,6,7,8,9,10}
                        Raise Addition of Parameters to the Power

  • python argparse_example_7.py -p 3 2 2

    OUTPUT

Namespace(param1=2, param2=2, power_to=3)

Param 1 : Type = <class 'int'>, Value = 2
Param 2 : Type = <class 'int'>, Value = 2

Addition of Param1 (2) & Param2 (2) Raised to Power 3 = 64

  • python argparse_example_7.py -p 11 2 2

    OUTPUT

usage: argparse_example_7.py [-h] [-p {2,3,4,5,6,7,8,9,10}] param1 param2
argparse_example_7.py: error: argument -p/--power-to: invalid choice: 11 (choose from 2, 3, 4, 5, 6, 7, 8, 9, 10)

Example 8: Arguments With Default Values

As a part of our eighth example, we have demonstrated how we can use default values for the parameter if the value is not provided. Our script of this part is exactly the same as the last part with minor addition in the add_argument() method of optional power parameter. We have introduced a new parameter named default with value 2. This will set the value of parameter power to 2 if we have not provided the power parameter from the command line.

Please make a note that we have also introduced another parameter in add_argument() method named dest. By default, the parameter value is stored in the Namespace instance by the name of the parameter. We can override this behavior by providing a key name where the parameter value should be stored. We have given power value to dest parameter hence Namespace instance keeps the value of optional power parameter in power key.

argparse_example_8.py
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("param1", help="First  Number for Operation", type=int)
parser.add_argument("param2", help="Second Number for Operation", type=int)
parser.add_argument("-p", "--power-to", help="Raise Addition of Parameters to the Power", type=int,
                    choices=[2,3,4,5,6,7,8,9,10], default=2, dest="power")

args = parser.parse_args()

print(args)

print("\nParam 1 : Type = %s, Value = %s"%(type(args.param1), args.param1))
print("Param 2 : Type = %s, Value = %s"%(type(args.param2), args.param2))

if args.power:
    res = (args.param1 + args.param2)**args.power
    print("\nAddition of Param1 (%d) & Param2 (%d) Raised to Power %d = %d"%(args.param1, args.param2, args.power, res))
else:
    print("\nAddition of Param1 & Param2 = ", args.param1 + args.param2)

Below we have run the script with different argument settings. We can notice that whenever we don't provide an optional power parameter, it sets the value of that parameter to 2 by default. In our earlier examples, it used to set the default value to None for optional parameters.


  • python argparse_example_8.py 2 2

    OUTPUT

Namespace(param1=2, param2=2, power=2)

Param 1 : Type = <class 'int'>, Value = 2
Param 2 : Type = <class 'int'>, Value = 2

Addition of Param1 (2) & Param2 (2) Raised to Power 2 = 16

  • python argparse_example_8.py --power-to 3 3

    OUTPUT

usage: argparse_example_8.py [-h] [-p {2,3,4,5,6,7,8,9,10}] param1 param2
argparse_example_8.py: error: the following arguments are required: param2

  • python argparse_example_8.py --power-to 3 3 3

    OUTPUT

Namespace(param1=3, param2=3, power=3)

Param 1 : Type = <class 'int'>, Value = 3
Param 2 : Type = <class 'int'>, Value = 3

Addition of Param1 (3) & Param2 (3) Raised to Power 3 = 216

Example 9: Enriching Help Message

As a part of our ninth example, we'll demonstrate how we can use the different parameters of ArgumentParser to decorate our help message. We have used the script from our fourth example again but have introduced many parameters when creating ArgumentParser instance.

Below is a list of parameters that are set in the script.

  • prog - This parameter accepts a string that is the name of the program. If we don't provide it then it'll be set to value sys.argv[0].
  • usage - This parameter accepts string specifying how we can use the program. If we don't provide it then it’s generated by default by the parser. Please check previous examples of help messages where the first line is a usage string.
  • description - This parameter accepts a string value that describes the program. It gets printed after usage and before listing of parameters in the help message.
  • epilog - This parameter accepts a string that gets printed at last in the help message.
  • add_help - This parameter accepts boolean value specifying whether to add -h/--h option to the parser or not. The default value is True hence they are added by default.
  • prefix_chars - This parameter accepts string value specifying characters that will be used as a prefix to declare the argument as optional. The default value of this parameter is "-".
  • argument_default - This parameter accepts a value that will set as the default value of all parameters.
argparse_example_8.py
import argparse

parser = argparse.ArgumentParser(prog="Program to Perform Addition of Two Numbers",
                                 usage="This program has two compulsory arguments which should be integer.\n\nHow to Run Script: argparse_example_9.py [-h] param1 param2",
                                 description="Program to Perform Addition of Two Numbers. This program takes two integer arguments as input and performs addition of them. It then prints result of addition to standard output.",
                                 epilog="This program simply adds two numbers by parsing arguments from the command line. It can extended to perform addition on many arguments in future.",
                                 add_help=True,
                                 prefix_chars="-",
                                 argument_default=0)

parser.add_argument("param1", help="First  Number for Operation", type=int)
parser.add_argument("param2", help="Second Number for Operation", type=int)

args = parser.parse_args()

print(args)

print("\nParam 1 : Type = %s, Value = %s"%(type(args.param1), args.param1))
print("Param 2 : Type = %s, Value = %s"%(type(args.param2), args.param2))

print("\nAddition of Param1 & Param2 = ", args.param1 + args.param2)

Below we have printed results of executing the script in different ways.


  • python argparse_example_9.py -h

    OUTPUT

usage: This program has two compulsory arguments which should be integer.

How to Run Script: argparse_example_9.py [-h] param1 param2

Program to Perform Addition of Two Numbers. This program takes two integer
arguments as input and performs addition of them. It then prints result of
addition to standard output.

positional arguments:
  param1      First Number for Operation
  param2      Second Number for Operation

optional arguments:
  -h, --help  show this help message and exit

This program simply adds two numbers by parsing arguments from the command
line. It can be extended to perform addition on many arguments in future.

  • python argparse_example_9.py 2

    OUTPUT

usage: This program has two compulsory arguments which should be integer.

How to Run Script: argparse_example_9.py [-h] param1 param2
Program to Perform Addition of Two Numbers: error: the following arguments are required: param2

  • python argparse_example_9.py 3 3

    OUTPUT

Namespace(param1=3, param2=3)

Param 1 : Type = <class 'int'>, Value = 3
Param 2 : Type = <class 'int'>, Value = 3

Addition of Param1 & Param2 =  6

This ends our small tutorial explaining how we can use the argparse module's API to parse command-line arguments efficiently. Please feel free to let us know your views in the comments section.

Sunny Solanki  Sunny Solanki

YouTube Subscribe Comfortable Learning through Video Tutorials?

If you are more comfortable learning through video tutorials then we would recommend that you subscribe to our YouTube channel.

Need Help Stuck Somewhere? Need Help with Coding? Have Doubts About the Topic/Code?

When going through coding examples, it's quite common to have doubts and errors.

If you have doubts about some code examples or are stuck somewhere when trying our code, send us an email at coderzcolumn07@gmail.com. We'll help you or point you in the direction where you can find a solution to your problem.

You can even send us a mail if you are trying something new and need guidance regarding coding. We'll try to respond as soon as possible.

Share Views Want to Share Your Views? Have Any Suggestions?

If you want to

  • provide some suggestions on topic
  • share your views
  • include some details in tutorial
  • suggest some new topics on which we should create tutorials/blogs
Please feel free to contact us at coderzcolumn07@gmail.com. We appreciate and value your feedbacks. You can also support us with a small contribution by clicking DONATE.


Subscribe to Our YouTube Channel

YouTube SubScribe

Newsletter Subscription