Python Argparse

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Topics Covered

Overview

Python argparse is a command line parsing module to get command line arguments (the input parameters passed to your scripts during program execution) into your program. Python provides various ways to deal with these arguments.

Some of the most common methods are : using sys.argv, using the getopt module, using the argparse module, and so on.

In this article, we will see how the python argparse module is effective and user-friendly. You can read about sys.argv and getopt here.

What is argparse Module in Python ?

Python argparse is used to accept arguments from the command line. As we have already seen, there are multiple ways to accept command line arguments, but using the argparse module is the most powerful way with minimal additional code required. Or, instead of having to manually set variables inside the code, the argparse module could be used to add reusability and flexibility to your code.

How to Create a Parser : Argparse Module Python

About :

To create a parser, first, we have to import the argparse module. After we have imported the argparse module, we now have to create a parser that will store all the necessary information that has to be passed from the command line.

Syntax :

Parameters :

  • prog :
    The name of the program (default: os.path.basename(sys.argv[0])).
  • usage :
    The string describing the program usage (default: generated from arguments added to parser).
  • description :
    Text to display before the argument help (default: none).
  • epilog :
    Text to display after the argument help (default: none).
  • parents :
    A list of ArgumentParser objects whose arguments should also be included.
  • formatter_class :
    A class for customizing the help output.
  • prefix_chars :
    The set of characters that prefix optional arguments (default: ‘-‘).
  • fromfile_prefix_chars :
    The set of characters that prefix files from which additional arguments should be read (default: None).
  • argument_default :
    The global default value for arguments (default: None).
  • conflict_handler :
    The 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).
  • exit_on_error :
    Determines whether or not ArgumentParser exits with error info when an error occurs. (default: True).

How to Add Arguments Using argparse

About :

Now we will provide information about the arguments to the ArgumentParser. For this, we'll use the add_argument() method. This information tells ArgumentParser how to take arguments from the command line and turn them into objects.

Syntax :

Parameters :

  • name or flags :
    Either a name or a list of option strings, e.g. foo or -f,--foo.
  • action :
    The basic type of action to be taken when this argument is encountered at the command line.
  • nargs :
    The number of command-line arguments that should be consumed.
  • const :
    A constant value required by some action and nargs selections.
  • default :
    The value produced if the argument is absent from the command line and if it is absent from the namespace object.
  • type :
    The type to which the command-line argument should be converted.
  • choices :
    A container of the allowable values for the argument.
  • required :
    Whether or not the command-line option may be omitted (optional only).
  • help :
    A 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().

How to Parse the Arguments Using argparse Module

About :

In the add_argument() method, we have provided the information about the arguments to the ArgumentParser. Initially, the data is stored in a sys.argv array in a string format. parse_args() converts argument strings to objects and assigns them as attributes of the namespace.

Previous calls to add_argument() determine exactly what objects are created and how they are assigned.

Syntax :

Parameters :

  • 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.

Examples

Example - 1 : Write a Program to Demonstrate a Basic Usage of argparse Library

Code :

Output :

As you can see, when I type python test.py only, this will throws an error because the required name argument is missing. Now, let's see the result when we add the --name argument.


Example - 2 : Write a Program to Multiply Two Integers Using Command-line

We can also make a program runnable without using the flag's name in the argument. We can use the positional arguments to eliminate the use of the --name flag before inputting the actual value.

Let's see two versions :
first without the positional argument and second with the positional argument.

Without positional arguments :

Output :

With positional arguments :

Output :

As you can see, positional arguments make the command-line cleaner, but sometimes it needs to specify more details about the arguments. To do this, we can simply use the help parameter in add_argument() to specify more details about the arguments. Let's see the below code to understand it more clearly.

Output :

Now, in the above output, we can see the details of the arguments.


Example - 3 : Write a Program to Find the Sum of Command-line Arguments Using argparse

Code :

Output :


Example - 4 : Write a Program to Find the Average of the Entered Command Line Numerical Arguments

Code :

Output :

Conclusion

  • Python argparse is a command line parsing module to get command line arguments (the input parameters passed to your scripts during program execution) into your program.
  • Instead of having to manually set variables inside the code, the python argparse module could be used to add reusability and flexibility to your code.
  • To create a parser, first, we have to import the argparse module. Now, create a parser that will store all the necessary information that has to be passed from the command line.
  • Filling an ArgumentParser with information about program arguments is done by making calls to the add_argument() method.
  • parse_args() convert argument strings to objects and assign them as attributes of the namespace.