The argparse Module in Python
The argparse module in Python serves as a versatile tool for building command-line interface (CLI) parsers. This module allows you to pass specific values to designated parameters in a sophisticated yet user-friendly manner.
Functionality: It simplifies the process of parsing command-line arguments for your program. Consider, for instance, running a program with the following command:
python script.py --name "Mario"
In this scenario, the module efficiently assigns the value "Mario" to the parameter "name."
Let's explore this with a hands-on example.
Begin by importing the `argparse` module into your Python script.
import argparse
Now, initiate a parser by creating an ArgumentParser object.
For instance, you might define an object named "parser." This object is your command-line command interpreter.
parser = argparse.ArgumentParser(description='Description of your program')
Next, you'll add arguments that your program will accept, using the add_argument method.
Each argument is declared individually, creating a structured namespace for the parser's arguments.
These can be either required or optional. For instance:
parser.add_argument('number', type=int, help='An integer number')
Here, "number" is a positional argument, meaning its value is based on the order of the parameters given, and it's defined as an integer (int).
You can add a brief description for each parameter under the 'Help' section.
To restrict values to a certain range, use the choices parameter. For example, to limit the range to between 0 and 5, write:
parser.add_argument('number', type=int, help='An integer number', choices=range(5))
Let's introduce another argument. For example:
parser.add_argument('--name', help='An optional argument')
Here, "--name" represents an optional argument, meaning it's linked to a specific option.
This setup tells the parser to expect an argument in the command line associated with the "name" attribute.
Naming a parameter makes its position in the command line flexible. Additionally, it's typically optional, but you can enforce its requirement by setting required=True.
parser.add_argument('--name', help='A mandatory argument', required=True)
Alternatively, you might assign a default value with the default parameter.
parser.add_argument('--name', help='An optional argument', default='Anonymous')
To finalize the setup, use the parse_args() method. This converts the command-line arguments into an object with accessible attributes.
args = parser.parse_args()
Once parsed, these arguments are accessible as attributes of the "args" object. Simply use a dot notation followed by the argument name to access them. For example:
print(args.number)
print(args.name)
Now, let's look at a comprehensive example of how to use this.
Write the following program and save it as "script.py" on your computer.
- import argparse
- # Create the parser
- parser = argparse.ArgumentParser(description='Example program.')
- # Add the arguments
- parser.add_argument('number', type=int, help='An integer number')
- parser.add_argument('--name', help='An optional name')
- # Parse the arguments
- args = parser.parse_args()
- # Use the arguments
- print('Number:', args.number)
- if args.name:
- print('Name:', args.name)
Running this script from the command line lets you input a number and, optionally, a name:
To run the program, use:
python script.py 5 --name "Mario"
The script correctly interprets these parameters.
Here, the first value (5) is linked to "number" as it appears first. The second value ("Mario") is tied to the "name" field.
The program then displays these arguments on the screen:
Number: 5
Name: Mario
Should you run the program with only the number 5, it operates seamlessly as the "name" attribute is optional.
python script.py 5
Number: 5
However, omitting the first argument (5) triggers an error since it's a required parameter.
python script.py --name "Mario"
usage: script.py [-h] [--name NAME] number
script.py: error: the following arguments are required: number
If you've documented the "help" attributes for your arguments, you can also display an inline help guide for your script.
For example, to access the help guide, run your program with the -h switch:
python script.py --name "Mario"
In this case, the script presents a detailed guide, listing all the acceptable arguments.
usage: script.py [-h] [--name NAME] number
Example program.
positional arguments:
number An integer number
options:
-h, --help show this help message and exit
--name NAME An optional name
This approach allows for the efficient and flexible management of both mandatory and optional program parameters.