About argparse Module in Python

Turhan Can Kargın
Dev Genius
Published in
6 min readMar 17, 2023

--

Hello!!! Argparse module is a module used in Python to get input from users for our programs. It is especially useful at the terminal interface. In this blog post, we will cover the argparse module in detail, learn how to use it, and better understand its usage with sample code snippets.

Example ‘argparse’ usage

Introduction:

When writing a Python program that requires input from users, programmers often use the input() function. However, this method is usually limited to simple input and is impractical for working with more complex input. In this case, using the argparse module makes it easier. The argparse module provides programmers with an easy-to-use interface to the command line interfaces of Python scripts. Besides, not every application we write has a graphical interface. Some applications are better suited to the command line, and these applications need some parameters. The argparse module generates help messages for the parameters we receive from the user, messages about how to use them. This module also suppresses the appropriate error message if the user enters an invalid parameter.

What is Argparse?

The Argparse module is a module used in Python to get input from users for our programs. It facilitates the management of user input for programs running on the command line. Programmers can predefine the values and options needed to get input, and users can run the program by specifying those values and options from the command line.

Advantages of Argparse:

By using the Argparse module, we can simplify the use of our Python scripts and make them more useful. The advantages of the Argparse module are:

  1. Provides a user-friendly interface.
  2. Allows programmers to predefine inputs.
  3. It ensures that inputs are of the right types.
  4. Allows us to write less code.

Creating a Parser:

First we need to import our module. After including our module, we create an object for our parser:

import argparse

Then we create a new object via ArgumentParser:

parser = argparse.ArgumentParser(description='This implentation does some work.')

Now we can add arguments.

Adding Argument:

After giving all the necessary information to the ArgumentParser object, we can add the arguments with the add_argument() function.

parser.add_argument('-i', '--firt_argument', nargs='+', required=False, help="This is the first argument")
parser.add_argument('-a', '--second_argument', required=False, help="This is the second argument")

Now let’s print and analyze our output with parser.print_help().

parser.print_help()

Note: Normally the argparse module is suitable for the command line, but when working in the interactive shell we will use the print_help() function of the argparse module to see the results.

Parsing Arguments:

The ArgumentParser object allows us to parse arguments using the parse_args() function. In our interactive shell:

parser.parse_args(['-a', '7'])

Output:

Namespace(firt_argument=None, second_argument='7')

Although we gave the parse_args function the parameter ‘-a’, our parser gave us the second name of the argument and the value we assigned to it to 7.

ArgumentParser Object:

Basically the structure of our ArgumentParser object:

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)

When a new ArgumentParser object is created, all arguments should be passed as keywords.

Arguments and Explanations:

  • prog: Name of the application (default: sys.argv[0])
  • usage: A text describing the intended use of the app (default: consists of parameters added to the app)
  • description: Display description text before the argument help (default: None)
  • epilog: Explanatory text that appears after the argument help (default: None)
  • parents: Includes arguments owned by a different ArgumentParser object.
  • formatter_class: Customizes help output.
  • prefix_chars: Sets the character prefixed to optional arguments (default: -)
  • fromfile_prefix_chars: The character set prefixing the file from which additional arguments should be read (default: None)
  • argument_default: Global value for arguments (default: None)
  • conflict_handler: Resolution strategy for conflicting arguments (usually redundant)
  • add_help: Adds the -h / -help option to the parser (default: True)
  • allow_abbrev: Allows long options to be abbreviated if abbreviations are not clear (Default: None)

add_argument() Function:

ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

Parameters and their descriptions:

  • name or flags: Array created to define names or options. Example: -s, -sil or delete.
  • action: Action to take if encountered on the command line.
  • nargs The number of command line arguments that should be used.
  • const: A constant value required by the choices of some action and nargs options.
  • default The default value if no arguments are found on the command line.
  • type: The type of value to convert the argument to.
  • choices: Sets a range of allowed values for arguments.
  • required: Used for whether the argument should be omitted (optional only)
  • help: Explanation about what the argument does.
  • metavar: A name for the argument in the usage messages.
  • dest: the name of the attribute to append to the object returned by parse_args().

name veya flags:

The add_argument() function needs to know whether it is an optional argument, such as -f or -foo, or a positional argument. The first arguments passed to add_argument() should therefore be an array flag or a simple argument name. For example, to add an optional argument:

parser.add_argument('-f', '--foo')

If we want to add a positional argument:

parser.add_argument('bar')

When the parse_args() function is called, optional arguments are defined by the — prefix and the remaining arguments are assumed to be positional: Let’s write the code:

import argparse
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('-f', '--foo')
parser.add_argument('bar')
print(parser.parse_args(['BAR']))
print(parser.parse_args(['BAR', '--foo', 'FOO']))
print(parser.parse_args(['--foo', 'FOO']))

Output:

Namespace(bar='BAR', foo=None)
Namespace(bar='BAR', foo='FOO')
usage: PROG [-h] [-f FOO] bar
PROG: error: the following arguments are required: bar

When we look at our output, our application threw an error because the bar argument is positional and we did not use it in the last parse_args() function.

help:

help takes the value as a string and contains help text about the arguments. Help texts appear when the user requests help (usually -h or — help).

import argparse

parser= argparse.ArgumentParser()
parser.add_argument('--foo', help='foo için yardım metni')
parser.add_argument('bar', help='bar için yardım metni')
print(parser.parse_args(['-h']))

Output:

usage: ilkprogram.py [-h] [--foo FOO] bar

positional arguments:
bar bar için yardım metni

optional arguments:
-h, --help show this help message and exit
--foo FOO foo için yardım metni

help includes various formatting methods. This way you can use your values in different places.

Sample Applications:

The following example code snippets show how to create a simple program using the argparse module.

Example 1: Entering Your Name:
This piece of code allows the user to enter their name:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("name", help="Please enter your name")
args = parser.parse_args()

print(f"Hello! {args.name}")

If you go to the file location where the project is located on the command line and enter ‘python <PROJECT NAME>.py <NAME>’, you will get the following output.

When the user enters their name, this code is copied into the args.name namespace and the user is given the message “Hello”.

Example 2: Finding the Sum of Two Numbers
This piece of code allows the user to enter two numbers and calculates the sum of those two numbers.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("number1", help="Enter an integer", type=int)
parser.add_argument("number2", help="Enter another integer", type=int)
args = parser.parse_args()

print(f"{args.number1} + {args.number2} = {args.number1 + args.number2}")

Conclusion:

The Argparse module is a very useful tool for creating command line interfaces. It can be used for everything from a simple program to a complex programming structure. This module lets users better control their programs and make the user experience better. The Argparse module can be used by any programmer in Python and is easy to learn.

Thank you for taking the time to read it. See you in the next articles.

--

--