Table of Contents
- Introduction
- Prerequisites
- Installation
- Basic Usage
- Adding Arguments
- Specifying Argument Types
- Setting Argument Defaults
- Handling Positional Arguments
- Handling Optional Arguments
- Working with Subcommands
- Conclusion
Introduction
In many Python applications, it is necessary to pass command line arguments to the program. The argparse
module in Python provides an easy and efficient way to parse command line arguments and options. It supports various types of arguments, allows setting default values, and even handles subcommands. In this tutorial, we will learn how to use the argparse
module to handle command line parsing in Python.
By the end of this tutorial, you will be able to:
- Install and import the
argparse
module in Python - Use
argparse
to parse and handle command line arguments - Define and validate different types of arguments
- Handle positional and optional arguments
- Implement subcommands for your command line application
Before starting this tutorial, it is recommended to have a basic understanding of Python programming and command line usage.
Prerequisites
To follow along with this tutorial, you need to have Python installed on your system. You can download Python from the official website python.org.
Installation
The argparse
module is included in the Python standard library, so there is no need to install any additional packages. We can directly import it into our Python script using the following import statement:
python
import argparse
Basic Usage
Let’s start with a simple example to understand the basic usage of the argparse
module. Create a new file called example.py
and add the following code:
```python
import argparse
# Create an ArgumentParser object
parser = argparse.ArgumentParser(description='My Command Line Program')
# Add an argument
parser.add_argument('name', type=str, help='Your name')
# Parse the arguments
args = parser.parse_args()
# Print the name
print(f"Hello, {args.name}!")
``` In the above code, we first import the `argparse` module. Then, we create an `ArgumentParser` object called `parser` with a description for our command line program.
Next, we add an argument using the add_argument()
method. The first argument is the name of the argument, followed by its expected type (str
in this case), and a help message. In this example, we expect the user to provide their name as a command line argument.
After adding the argument, we parse the command line arguments using the parse_args()
method of the parser
object. This will parse the arguments provided by the user and store the values in the args
variable.
Finally, we print a simple greeting message using the provided name.
To run this program, open a terminal or command prompt, navigate to the directory where the example.py
file is located, and run the following command:
python example.py John
You should see the following output:
Hello, John!
Congratulations! You have successfully used the argparse
module to parse and handle a basic command line argument.
Adding Arguments
In the previous example, we added a single argument to our command line program. However, argparse
allows us to add multiple arguments with different types.
Let’s enhance our script to accept both a name and an age from the user. Modify the example.py
file as follows:
```python
import argparse
# Create an ArgumentParser object
parser = argparse.ArgumentParser(description='My Command Line Program')
# Add arguments
parser.add_argument('name', type=str, help='Your name')
parser.add_argument('age', type=int, help='Your age')
# Parse the arguments
args = parser.parse_args()
# Print the user details
print(f"Name: {args.name}")
print(f"Age: {args.age}")
``` In this code, we added another argument called `age`. It expects an integer value from the user. We can access the value of each argument using the `args` object.
Now, run the program with the following command:
python example.py John 25
You should see the following output:
Name: John
Age: 25
Now you can see that the script is able to handle multiple arguments. You can add more arguments to your command line program by calling the add_argument()
method for each one.
Specifying Argument Types
When adding arguments, we can specify their expected types. The argparse
module provides various built-in types to handle different types of arguments, such as strings, integers, floats, booleans, and more.
Let’s modify our script to accept a float value for the age instead of an integer. Modify the example.py
file as follows:
```python
import argparse
# Create an ArgumentParser object
parser = argparse.ArgumentParser(description='My Command Line Program')
# Add arguments
parser.add_argument('name', type=str, help='Your name')
parser.add_argument('age', type=float, help='Your age')
# Parse the arguments
args = parser.parse_args()
# Print the user details
print(f"Name: {args.name}")
print(f"Age: {args.age}")
``` Now, run the program with the following command:
```
python example.py John 25.5
``` You should see the following output:
```
Name: John
Age: 25.5
``` Here, we changed the type of the `age` argument to `float`. Now the script accepts floating-point values for the age.
The argparse
module also allows us to specify custom types by creating our own functions. However, using the built-in types provided by argparse
will be sufficient for most cases.
Setting Argument Defaults
Sometimes, we may want to provide default values for certain arguments. The argparse
module allows us to set defaults for arguments, so if the user doesn’t provide a value for that argument, the default value will be used.
Let’s modify our script to provide a default value for the age
argument. Modify the example.py
file as follows:
```python
import argparse
# Create an ArgumentParser object
parser = argparse.ArgumentParser(description='My Command Line Program')
# Add arguments
parser.add_argument('name', type=str, help='Your name')
parser.add_argument('age', type=float, help='Your age', default=30.0)
# Parse the arguments
args = parser.parse_args()
# Print the user details
print(f"Name: {args.name}")
print(f"Age: {args.age}")
``` In this code, we added a `default` parameter to the `add_argument()` method of the `age` argument. The default value is set to `30.0`. If the user doesn't provide a value for the age, the default value will be used.
Now, run the program with the following command:
python example.py John
You should see the following output:
Name: John
Age: 30.0
As you can see, since we didn’t provide a value for the age argument, it used the default value specified in the script.
Handling Positional Arguments
So far, we have been handling arguments in the order they were provided on the command line. These are called positional arguments. However, the argparse
module also allows us to specify arguments with optional names, known as optional arguments.
Let’s modify our script to handle a positional argument and an optional argument. Modify the example.py
file as follows:
```python
import argparse
# Create an ArgumentParser object
parser = argparse.ArgumentParser(description='My Command Line Program')
# Add a positional argument
parser.add_argument('name', type=str, help='Your name')
# Add an optional argument
parser.add_argument('-a', '--age', type=float, help='Your age')
# Parse the arguments
args = parser.parse_args()
# Print the user details
print(f"Name: {args.name}")
print(f"Age: {args.age}")
``` In this code, we added an optional argument using the `add_argument()` method. The argument begins with a single hyphen `-` followed by a single character flag (`a` in this case). We also added a long-form flag `--age` for the same argument. The user can provide the value for this argument by using either the short flag `-a` or the long flag `--age`.
Now, run the program with the following command:
python example.py John --age 25.5
You should see the following output:
Name: John
Age: 25.5
Here, we provided the value for the age
argument using the long flag --age
. You can also use the short flag -a
:
python example.py John -a 25.5
The output will be the same.
If we don’t provide a value for the age
argument, it will be None
:
python example.py John
Output:
Name: John
Age: None
Positional arguments are required by default, meaning the user must provide a value for them. If a required argument is not provided, the argparse
module will raise an error. However, if you want to make an argument optional, you can use optional arguments, which we will cover next.
Handling Optional Arguments
Optional arguments are arguments that the user may or may not provide. They are specified with one or more hyphens (-
).
Let’s enhance our script to handle an optional verbose flag. Modify the example.py
file as follows:
```python
import argparse
# Create an ArgumentParser object
parser = argparse.ArgumentParser(description='My Command Line Program')
# Add a positional argument
parser.add_argument('name', type=str, help='Your name')
# Add an optional argument
parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose mode')
# Parse the arguments
args = parser.parse_args()
# Print the user details
print(f"Name: {args.name}")
if args.verbose:
print("Verbose mode enabled")
``` In this code, we added an optional argument called `verbose`. The argument begins with a single hyphen `-v` followed by a single character flag. We also added a long-form flag `--verbose` for the same argument. The `action` parameter is set to `'store_true'`, which means that if the user provides this argument, its value will be `True`. If the user doesn't provide the argument, its value will be `False`.
Now, run the program with the following command:
python example.py John -v
Output:
Name: John
Verbose mode enabled
Here, we used the short flag -v
to enable verbose mode. You can also use the long flag --verbose
. If the verbose flag is not provided, the verbose mode will be disabled.
python example.py John
Output:
Name: John
The verbose mode is disabled.
Optional arguments allow us to provide additional functionality to our command line program without complicating the usage with multiple positional arguments.
Working with Subcommands
The argparse
module also supports subcommands. Subcommands allow us to group related functionality under a command and handle them separately.
Let’s modify our script to handle two subcommands: add
and multiply
. Modify the example.py
file as follows:
```python
import argparse
# Create an ArgumentParser object
parser = argparse.ArgumentParser(description='My Command Line Program')
# Create subparsers for the subcommands
subparsers = parser.add_subparsers(dest='subcommand', help='Subcommands')
# Subcommand: add
add_parser = subparsers.add_parser('add', help='Add two numbers')
add_parser.add_argument('x', type=int, help='First number')
add_parser.add_argument('y', type=int, help='Second number')
# Subcommand: multiply
multiply_parser = subparsers.add_parser('multiply', help='Multiply two numbers')
multiply_parser.add_argument('x', type=int, help='First number')
multiply_parser.add_argument('y', type=int, help='Second number')
# Parse the arguments
args = parser.parse_args()
# Perform the operation based on the subcommand
if args.subcommand == 'add':
result = args.x + args.y
print(f"Sum: {result}")
elif args.subcommand == 'multiply':
result = args.x * args.y
print(f"Product: {result}")
``` In this code, we first create subparsers using the `add_subparsers()` method of the `ArgumentParser` object. We assign the subcommands to the `subcommand` variable using the `dest` parameter.
For each subcommand, we create a separate subparser using the add_parser()
method of subparsers
. We specify the name, help message, and the expected arguments for each subcommand.
Finally, we check the value of the subcommand
variable and perform the corresponding operation based on the chosen subcommand.
Now, run the program with the following commands:
python example.py add 10 20
Output:
Sum: 30
python example.py multiply 5 6
Output:
Product: 30
Here, we provide the subcommand name as the first argument, followed by the required arguments for that subcommand.
Subcommands are useful when we have multiple operations or functionalities within a command line program. They allow us to organize the functionality in a more structured and user-friendly way.
Conclusion
In this tutorial, we learned how to use the argparse
module in Python to parse and handle command line arguments. We covered the basic usage of the module, adding arguments, specifying argument types, setting argument defaults, handling positional and optional arguments, and implementing subcommands.
The argparse
module provides a flexible and powerful way to handle command line parsing in Python. By using argparse
, you can easily create command line applications that can be controlled by the users without modifying the source code.
Now that you have a good understanding of the argparse
module, you can start using it in your own Python projects to handle command line arguments and make your applications more interactive and user-friendly.