This tutorial is going to walk you through how to use the argparse module to pass command line arguments to a Python script.

Argparse is just one way to pass command line arguments in Python. In another tutorial, we also showed you how to pass command line arguments with sys.argv.

While the default sys.argv list can be handy for capturing basic command line arguments in a Python list, it lacks advanced features such as optional arguments and argument grouping using subparsers. The Python argparse module provides these functionalities, which we’ll explore in this tutorial.

Creating an Argument Parser

The argparse module is a default Python module that comes prebuilt with your Python installation.

To use the argparse module, you need to perform the following steps.

  1. Import the argparse module.
  2. Create an object of the argparse.ArgumentParser class. You can pass the description of the parser to the description attribute. The description is displayed using -h or --help command.
  3. Define a command line argument variable using the add_argument argument method of the ArgumentParser object. You need to pass the values for the argument name and, optionally, you can pass the type and a help description.
  4. Parse command line arguments using the parse_args() method.
  5. Retrieve values of the parsed arguments using the dot operator.

The following script defines the parser argument parser that captures one positional argument, name, displayed on the console output.

import argparse

#Create a parser object
parser = argparse.ArgumentParser(description='Greet User')

#Add a positional argument
parser.add_argument('name', type=str, help='Name of the user')

#Parse the arguments
args = parser.parse_args()

#Print the greeting
print(f"Welcome, {args.name}!")

Using an Argument Parser

You must pass values for the positional command line arguments after the python file_name.py command to use argument parsers. The position of the argument passed in the command prompt must match the position of the argument in your Python script. Since we only have a single argument in the script above, you can pass its value like this:

python main.py Jack

Output:

Welcome, Jack!

The above output displays the value for the name command line argument.

Getting Help for an Argument Parser

If you need help passing a command line argument in a script, you can use the help function as follows. The help function will tell you how to pass the command line arguments along and, if the developer set up a nice description, the description of each argument will also appear.

python main.py -h

Output:

usage: main.py [-h] name

Greet User

positional arguments:
  name        Name of the user

options:
  -h, --help  show this help message and exit

Argument Parser with Optional Arguments

Positional arguments in the ArgumentParser object are mandatory. If you don’t pass values for the positional argument, you’ll get an error like this:

usage: main.py [-h] name
main.py: error: the following arguments are required: name

You can add an optional argument in argparse by prefixing -- with the argument name. You can also pass a default value for an optional argument.

In the following script, we define a positional argument, name, and an optional argument --age, with a default value 25.

import argparse

#Create a parser object
parser = argparse.ArgumentParser(description='Greet User')

#Add a positional argument
parser.add_argument('name', type=str, help='Name of the user')

#Add an optional argument for the user's age
#Note the use of '--age' to indicate that it is an optional argument
parser.add_argument('--age', type=int, default=25, help='Age of the user')

#Parse the arguments
args = parser.parse_args()

#Print the greeting
greeting = f"Welcome, {args.name}!"

#If Age is provided, add it to the greeting
if args.age:
    greeting += f" You are {args.age} years old."

print(greeting)

To run a Python script containing an optional argument, you must pass the optional argument value by prefixing --. It’s important to note that the position of the positional argument must match its declaration in the script. On the other hand, the position of the optional argument doesn’t matter, and you can call it in any order using the -- prefix.

The following command runs the main.py script with positional and optional arguments.

python main.py Jack --age 30

Output:

Welcome, Jack! You are 30 years old.

If you run the above script with only the positional argument, the console will display the default value for the positional argument.

python main.py Jack

Output:

Welcome, Jack! You are 25 years old.

Code More, Distract Less: Support Our Ad-Free Site

You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.


Creating Subparsers

One of the most exciting features of the Python argparse module is its ability to create subparsers. Subparsers allow you to create groups for different types of command line arguments.

Consider a scenario where you want to create command line arguments for greeting a user and updating its record. With subparsers, you can create two distinct parsers: one for dealing with greetings and another for updating records.

To create a subparser, you need to perform the following steps:

  1. Create an object of the argparse.ArgumentParser class.
  2. Create a subparser object using the add_subparsers() method of the ArgumentParser class object.
  3. Create multiple subparsers using the add_parser() method of the subparser object.

In the following script, we create two subparsers: greet and update. The greet subparser parses command line arguments for greeting e.g. name and --age.

The update subparser parses command line arguments employee_id, --name, and age. The update parser then updates a fictional updates list with the parsed arguments and displays updated values on the console.

import argparse

#Create the main parser object
parser = argparse.ArgumentParser(description='Employee Management System')

#Add subparsers to the main parser
subparsers = parser.add_subparsers(dest="command", help='Commands')

#Create a subparser for the 'greet' command
greet_parser = subparsers.add_parser('greet', help='Greet a user')
greet_parser.add_argument('name', type=str, help='Name of the user')
greet_parser.add_argument('--age', type=int, help='Age of the user')

#Create a subparser for the 'update' command
update_parser = subparsers.add_parser('update', help='Update employee data')
update_parser.add_argument('employee_id', type=str, help='Employee ID')
update_parser.add_argument('--name', type=str, help='New name of the employee')
update_parser.add_argument('--age', type=int, help='New age of the employee')

#Parse the arguments
args = parser.parse_args()

#Execute actions based on the command used
if args.command == 'greet':
    greeting = f"Welcome, {args.name}!"
    if hasattr(args, 'age') and args.age:
        greeting += f" You are {args.age} years old."
    print(greeting)
elif args.command == 'update':
    updates = []
    if hasattr(args, 'name') and args.name:
        updates.append(f"name to {args.name}")
    if hasattr(args, 'age') and args.age:
        updates.append(f"age to {args.age}")
    if updates:
        update_str = ", ".join(updates)
        print(f"Updating employee {args.employee_id} with {update_str}")
    else:
        print(f"No updates provided for employee {args.employee_id}")
else:
    parser.print_help()

To call subparsers, you must first pass the subparser name followed by command line arguments for the subparser. For example, the following script runs the script by passing values for the greet subparser.

python main.py greet Jack --age 30

Output:

Welcome, Jack! You are 30 years old.

Similarly, the script below calls the update subparser using one positional (employee_id) and two optional (--name, --age) arguments.

python main.py update E105 --name Jack-Robins --age 32

Output:

Updating employee E105 with name to Jack-Robins, age to 32

Conclusion

In conclusion, the Python argparse module is handy for easily parsing command line arguments in Python. I use it for many of my utility scripts to provide enhanced flexibility. With its ability to provide positional and optional arguments and subparsers, you can use it to create highly customized Python scripts for running on a terminal.


Code More, Distract Less: Support Our Ad-Free Site

You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.