Python argparse Module Guide

By
Vladimir Kaplarevic
Published:
November 27, 2025
Topics:

Many developers use text editors and IDEs to write Python code and test different scenarios. However, on servers or remote machines, the command line is often the preferred way to run and control scripts.

The argparse module allows you to build programs that accept command-line arguments, validate user input, and control the script's behaviour.

Learn how to use argparse to build a fully working CLI and extend it with optional arguments and validation rules.

Guide about the Python argparse module.

Prerequisites

What Is Python argparse Module?

The argparse module is a native Python tool for creating command-line interfaces (CLIs). Developers use it to define the interface, arguments, options, and usage instructions for their programs.

Users can then interact with the CLI by typing commands in the terminal. argparse reads (parses) the raw text the user enters in the terminal, understands it, and converts it into usable values that Python can process.

The argparse module:

  • Recognizes which options the user entered.
  • Checks if the options are valid.
  • Converts values to the correct Python data types.
  • Returns an error message in case something goes wrong.
  • Provides --help output.

Python argparse Use Cases

Creating a CLI with argparse is frequently used to:

  • Run scripts on remote machines. Passing parameters through the terminal over SSH is still the simplest way to control a script. A CLI behaves consistently across different environments and operating systems, which is essential on servers without graphical interfaces (GUIs).
  • Process files and directories dynamically. You can use command-line arguments to pass file paths, directory locations, and other settings directly into a script without needing to open or modify the code itself.
  • Switch between different program modes. If a script supports multiple behaviors, argparse can define modes and sub-commands, and let you switch between them using a single command-line flag.
  • Build data analysis tools. Building a small CLI can help when you need to develop custom filters, sorting options, or summary functions for large datasets without using Jupyter Notebook or writing a full application.
  • Automate repetitive tasks. CLI-driven scripts are ideal for cron jobs, monitoring tools, CI/CD pipelines, and other automation workflows. They are quick to build, easy to configure with arguments, and they work in different environments.

How to Build a CLI with argparse?

argparse is part of the standard Python library, so there is no need to install it separately. You only need to import the module and start defining your CLI in a Python script.

Note: The examples in this guide are presented from the Ubuntu 24.04 command line.

Step 1: Create Script and Import argparse

Use a text editor or IDE to create a new Python file.

In this example, nano is used to create the CLI script:

nano examplecli.py

Add the following line at the top of the file:

import argparse
Importing the argparse module in Python script.

This imports the argparse module and prepares the script for the command-line arguments.

Step 2: Create ArgumentParser

The ArgumentParser object holds the CLI definition, including its description, help text, and the arguments the script accepts. The following example shows how to build a simple CLI that calculates transaction fees.

To create an ArgumentParser object, add the following code to the script:

parser = argparse.ArgumentParser(
        description="Calculate Transaction Fees"
)
Create an ArgumentParser object in argparse script.

The parser is now ready to accept arguments that define what users can type and what values the script should expect. There are two main argument types: positional arguments and optional arguments.

Step 3: Add Positional Arguments

A positional argument is identified by its position in the command. It is mandatory, and the user must provide it in the correct order for the script to work.

Use the add_argument() function to add a positional argument under the ArgumentParser() object:

parser.add_argument("amount", type=float, help="Transaction Amount")

In this example, the positional argument is amount, and the expected value type is a floating-point number (float).

Adding arguments in argparse script.

Because amount is a positional argument; the user must provide the value right after the script name:

python3 examplecli.py <amount>

If the user runs the script without the required amount, argparse displays an error message indicating that a required argument is missing.

Step 4: Parse Arguments

Parsing converts the user's terminal input into Python variables your script can use. Basic parsing is performed using a single line:

args = parser.parse_args()

The argparse module reads everything the user typed after the script name, matches those inputs to the arguments you defined, validates them, and stores the results inside an args object.

Parsing input in argparse Python.

After parsing, each argument becomes a Python attribute:

args.<argument_name>

For example, you can now reference the positional argument amount by using:

args.amount

By referencing these attributes later in the code, you enable the script to respond dynamically to user input.

Step 5: Define Program Logic

Once argparse parses the user's input and stores the values in the args object, you can use those values inside the program logic. The script performs an action based on the arguments the user provided.

Note: Comments in Python are a good practice, and you will see them throughout the code examples in this guide.

For example, you can add a simple default behavior to calculate a processing fee. In this case, card transactions incur a 5.5% processing fee:

fee_rate = 0.055       # 5.5% card processing fee

gross = args.amount
fee = gross * fee_rate
net = gross - fee

print(f"Gross Amount: {gross:.2f}")
print(f"Processing Fee (5.5% Card): {fee:.2f}")
print(f"Net Amount: {net:.2f}")
Adding program logic to argparse Python script.

The amount positional argument, which is the number the user enters in the terminal, is used as a basis to calculate the processing fee and net amount.

Step 6: Run Script

After creating the ArgumentParser object, adding positional arguments, and defining the program logic, test the script from the terminal:

1. Save the changes and close the file. If using nano, press Crtl+X, then y, and Enter.

2. Use the following command to run the script and enter an amount to calculate processing fees. For example:

python3 examplecli.py 95

Based on the arguments in the command, Python calculates the processing fee and displays the net amount.

CLI created with argparse in Python.

3. If you execute the script without the positional amount argument, argparse displays an error message.

Missing argument argparse error.

This occurs because the script cannot run without the required amount input.

4. In case of errors, argparse generates help output automatically based on the information in the ArgumentParser object.

Use the -h flag to display the help page:

python3 examplecli.py -h
argparse help page in Python.

The built-in help menu means that your tools are easy to understand and clearly documented from day one.

Advanced Argument Parsing

After creating a basic CLI, you can extend it with optional arguments and validation rules to guide user input and offer more options. Refer to the sections below for examples.

Adding Optional Arguments

Optional arguments give users more control of how a script behaves. Unlike positional arguments, the order in the command line is not relevant. Because they are optional, users must type a dash (-) or a double dash (--) followed by an explicit flag to name the argument.

To continue with the example from the previous section, you can allow users to choose a different payment method to adjust the processing fee.

1. Add the following optional argument under the positional argument in the examplecli.py script:

# Optional Argument (Payment Method)
parser.add_argument(
          "--method",
          choices=["card", "sepa", "ach", "wallet"],
          default="card",
          help="Payment Method (default: card)."
)

This argument allows the user to select one of the listed methods and defaults to card if the --method flag is not provided.

2. Replace the previous fixed fee_rate with a dictionary that maps each method to its fee percentage:

# Fee Calculation Logic
fee_rates = {
        "card": 0.055,
        "sepa": 0.010,
        "ach": 0.005,
        "wallet": 0.030
}

fee_rate = fee_rates[args.method]

3. Modify the relevant print statement so it reflects the selected payment method:

print(f"Gross Amount: {gross:.2f}")
print(f"Processing Fee ({fee_rate*100:.1f}% {args.method}): {fee:.2f}")
print(f"Net Amount: {net:.2f}")

This is the full code example:

import argparse

# ArgumentParser
parser = argparse.ArgumentParser(
        description="Calculate Transaction Fees"
)

# Positional Argument
parser.add_argument("amount", type=float, help="Transaction Amount")

# Optional Argument (Payment Method)
parser.add_argument(
          "--method",
          choices=["card", "sepa", "ach", "wallet"],
          default="card",
          help="Payment Method (default: card)."
)

# Parse Arguments
args = parser.parse_args()

# Fee Calculation Logic
fee_rates = {
        "card": 0.055,
        "sepa": 0.010,
        "ach": 0.005,
        "wallet": 0.030
}

fee_rate = fee_rates[args.method]

gross = args.amount
fee = gross * fee_rate
net = gross - fee

# Output
print(f"Gross Amount: {gross:.2f}")
print(f"Processing Fee ({fee_rate*100:.1f}% {args.method}): {fee:.2f}")
print(f"Net Amount: {net:.2f}")

4. Test the script from the terminal:

python3 examplecli.py 50

The --method flag was not used, and argparse defaults to card.

Using a flag for optional argument.

5. Now use the --method flag to calculate the fee for the SEPA payment option:

python3 examplecli.py 66 --method sepa
Using optional arguments in Python argparse.

Since optional arguments do not rely on position, the following command also works:

python3 examplecli.py --method sepa 66
Using optional flag in argparse.

They produce the same output because argparse identifies optional arguments by their flag.

nargs and Multiple Values

Each argument in argparse accepts a single value. The nargs= keyword associates multiple command-line arguments with a single action. You can specify how many values an argument can accept using the following nargs= patterns:

nargDescription
NAn exact number of values.
?Zero or one value.
*Zero or more values.
+One or more values.

For example, use nargs= to calculate fees for multiple transactions in a single command:

1. Edit the positional argument in the examplecli.py script to use nargs="+":

# Positional Argument
parser.add_argument(
       "amount",
       type=float,
       nargs="+",
       help="One or More Transaction Amounts."
)

2. Update the Fee Calculation Logic section to loop over amounts:

# Fee Calculation Logic
fee_rates = {
        "card": 0.055,
        "sepa": 0.010,
        "ach": 0.005,
        "wallet": 0.030
}

fee_rate = fee_rates[args.method]

for amount in args.amount:
    gross = amount
    fee = gross * fee_rate
    net = gross - fee

    print(f"Gross Amount: {gross:.2f}")
    print(f"Processing Fee ({fee_rate*100:.1f}% {args.method}): {fee:.2f}")
    print(f"Net Amount: {net:.2f}")
    print() # Adding a space between entries.

Now the user can pass several amounts at once:

python3 examplecli.py 22 46 77

Since nargs="+" means one or more values, the argument behaves like an incremental list in your script.

Using nargs parameter in argparse.

Optionally, test the --method flag to confirm it also works with nargs=:

python3 examplecli.py 22 46 77 --method sepa
Combining optional parameters with nargs in argparse.

Note: Learn about the different ways to add elements to a list in Python. It is one of the most common tasks in Python development.

Adding Boolean Toggles

A Python Boolean is a data type that only has two values: True and False. In argparse, Boolean flags are optional arguments that act as switches to turn a feature on or off. They are defined using the action= parameter.

The most common pattern is:

action="store_true"

This means that if the user includes the flag, the value is True; if the flag is omitted, the value is False. To add a Boolean toggle to the examplecli.py script:

1. Add the --verbose flag as an optional argument after the other ars.argument() calls, and before args = parser.parse_args():

# Optional Argument 2 (Boolean Toggle)
parser.add_argument(
        "--verbose",
        action="store_true",
        help="Detailed Calculation"
)

If the user includes the --verbose flag in their command, they will receive a more detailed account of the fee calculation.

Adding a Boolean handle in argparse.

2. Add the verbose logic after the fee and net values are calculated:

 if args.verbose:
      print("=== Fee Calculation Details ===")
      print(f"Method:    {args.method}")
      print(f"Fee Rate:     {fee_rate * 100:.2f}%")
      print(f"Gross Amount: {gross:.2f}")
      print(f"Processing Fee  {fee:.2f}")
      print(f"Net Amount: {net:.2f}")
      print() # Adding a space between entries.
 else:
      print(f"Gross Amount: {gross:.2f}")
      print(f"Processing Fee:  {fee:.2f}")
      print(f"Net Amount: {net:.2f}")
      print() # Adding a space between entries.
Adding verbose logic to Boolean handle in argparse.

Run the CLI without the verbose flag:

python3 examplecli.py 44

Test the Boolean toggle by using the --verbose flag:

python3 examplecli.py 44 --verbose

Python calculates the fees and displays the transaction details:

Using the verbose flag in argparse.

You can combine verbose with other optional arguments, such as --method, as well as calculate multiple values with nargs=:

python3 examplecli.py 44 58 102 --verbose --method ach
Multiple arguments using Boolean handles in argparse.

argparse evaluates the optional arguments correctly, regardless of the order they are entered in.

Validating User Input

By introducing validation rules in scripts, you can prevent invalid data from reaching the program logic. argparse ensures users run the script correctly by:

  • Enforcing the required data type for each argument.
  • Preventing users from entering incorrect or unexpected values.
  • Restricting arguments to a defined range or set of values.
  • Providing clear, user-friendly error messages.

The argparse module provides several built-in methods for validating user input.

Enforcing Data Types

The type= parameter specifies the data type that a specific argument expects. If the user enters a value of the wrong type, argparse rejects it automatically and displays an error.

For example, in the examplecli.py script, the type= parameter for the amount positional argument ensures that users can only enter floating-point numbers:

# Positional Argument
parser.add_argument(
       "amount",
       type=float,
       nargs="+",
       help="One or More Transaction Amounts."
)

If the user tries to enter a value that cannot be converted to a float, like a string, argparse stops execution.

Enforcing a data type in argparse.

The error message informs the user that the provided value is not a float.

Restricting Values with choices

The choices= parameter allows you to define a preselected list of values that an argument is limited to. It is mainly used when an argument must match a set of known categories.

In the examplecli.py script, choices= limits the type of transactions the logic applies to:

# Optional Argument (Payment Method)
parser.add_argument(
          "--method",
          choices=["card", "sepa", "ach", "wallet"],
          default="card",
          help="Payment Method (default: card)."
)

When the user provides the --method flag, argparse will accept only one of the four valid payment types: card, sepa, ach, or wallet.

Using the choices parameter in argparse.

If the user enters a value not on the list, an error message with relevant help text, including a list of valid options, is displayed.

Cross-Argument Parsing

In real-world applications, business rules often depend on more than one input. To support more complex validation, you need to check multiple arguments together and enforce rules that apply only in certain combinations, called cross-argument validation.

These checks are performed after parsing. Using the examplecli.py script example, add rules that enforce minimum transaction amounts for ACH and SEPA payments.

Place the following code after the Parse Arguments section and before the Fee Calculation Logic:

# Cross-Argument Validation
for value in args.amount:
    if args.method == "ach" and value < 0.50:
          parser.error("ACH Transaction must be at least $0.50.")
    if args.method == "sepa" and value < 1:
          parser.error("SEPA transaction must be at least $1.00.")

Now, if the user enters an amount below the required minimum, an error message appears that explains why the input is invalid.

Using cross-argument validation in argparse.

Note: Find out how to iterate over sequence-like data structures by using a Python for loop.

Adding Custom Constraints

You can perform additional checks after parsing to enforce validation rules that argparse does not handle automatically.

One practical example is to limit the amount of data a user can enter at once. If a user pastes hundreds or thousands of values into the terminal, the script can reject the input before it starts processing.

For a practical demonstration, modify the examplecli.py script to limit the number of amounts to 20.

Place the following code after the Parse Arguments section and before the Fee Calculation Logic:

# Automatic List Validation
MAX_TX = 20
if len(args.amount) > MAX_TX:
    parser.error(f"Too many amounts provided. Maximum allowed is {MAX_TX}.")

If you run the script with more than 20 values, it displays an error immediately.

Adding custom constraints in the argparse module.

The message clearly explains how to resolve the issue.

Advantages and Disadvantages of Python argparse

Using the argparse module has several clear advantages, especially when creating simple, small CLIs. However, as applications grow in size and complexity, it may become harder to scale compared to more modern libraries.

argparse Advantages

The benefits of using argparse include:

  • It is compatible across different platforms. A CLI built with argparse works on any Linux distribution, macOS, and Windows, as long as Python is installed.
  • No need to write separate documentation. argparse automatically generates a professional help page as soon as you define the arguments. Users can run -h or --help and understand how to use the script from the get-go.
  • Script behavior can be controlled from the terminal. Users can change how the script behaves by passing arguments in the command line.
  • Helpful error messages. When a user makes an input error, argparse returns a clear, standardized error message. This keeps the scripts predictable and easier to troubleshoot.
  • Advanced argument patterns. argparse can handle multiple values, argument groups, Boolean toggles, and validation rules for building more complex CLIs.

argparse Disadvantages

The argparse module also has several disadvantages:

  • Becomes harder to manage as CLIs grow. If a tool requires many arguments and subcommands, the script can feel verbose and difficult to structure. This is especially an issue when a CLI needs to scale.
  • Not as modern as newer libraries. While argparse is reliable and stable, it is not as developer-friendly as modern libraries that offer cleaner syntax and helpful features like automatic type hints.
  • Requires more manual work. argparse can handle complex CLIs. However, setting up multiple subcommands often requires more boilerplate code and micromanagement compared to modern CLI frameworks.

Conclusion

After completing the steps in this guide, you have a fully functional CLI program created with the argparse module. From here, continue improving the existing code or try new ideas.

When the project is ready, use Git to save and manage your work.

Was this article helpful?
YesNo