Skip to main content

How to Add Multiple Command-Line Arguments in Python Argparse

The argparse module is the standard Python solution for building command-line interfaces. While adding a single argument is straightforward, real-world applications often require a combination of positional arguments, optional flags, and lists of inputs.

This guide explains how to define and manage multiple arguments effectively, ensuring your script handles inputs robustly and generates helpful error messages automatically.

Understanding Argument Types

Before adding multiple arguments, it is crucial to distinguish between the two main categories:

  • Positional Arguments: Mandatory. Their meaning is defined by the order in which they appear (e.g., cp source destination).
  • Optional Arguments: Optional (usually). They use prefixes like - or -- and can appear in any order (e.g., --verbose, --output file.txt).

To add multiple arguments, you simply call parser.add_argument() sequentially for each parameter you need.

Method 1: Adding Multiple Positional Arguments

When you define multiple positional arguments, argparse assigns values based on the order the user provides them in the command line.

Scenario: A File Copy Script

We need two arguments: a source file and a destination file.

import argparse

parser = argparse.ArgumentParser(description="Copy file content.")

# ⛔️ Incorrect: Relying on sys.argv manually is fragile and lacks validation
# source = sys.argv[1]
# dest = sys.argv[2]

# ✅ Correct: Define arguments sequentially
parser.add_argument("source", help="The file to read from")
parser.add_argument("destination", help="The file to write to")

args = parser.parse_args()

print(f"Copying from '{args.source}' to '{args.destination}'")

Output:

$ python script.py data.txt backup.txt
Copying from 'data.txt' to 'backup.txt'
warning

Order matters! If the user runs python script.py backup.txt data.txt, the script will read from backup.txt. Ensure your help strings clearly define what each position represents.

Method 2: Mixing Positional and Optional Arguments

Most robust scripts mix mandatory positional arguments with optional configuration flags. Optional arguments are defined by adding - or -- to the name.

Scenario: A Calculator with a Verbose Flag

We need two numbers (positional) and a verbose flag (optional) to print detailed output.

import argparse

parser = argparse.ArgumentParser(description="Simple Adder")

# 1. Add Positional Arguments (Order matters)
parser.add_argument("num1", type=float, help="First number")
parser.add_argument("num2", type=float, help="Second number")

# 2. Add Optional Argument (Flag)
# 'store_true' means the variable becomes True if the flag is present, False otherwise.
parser.add_argument("-v", "--verbose", action="store_true", help="Increase output verbosity")

args = parser.parse_args()

result = args.num1 + args.num2

# ✅ Correct: Using the flag logic
if args.verbose:
print(f"The result of adding {args.num1} and {args.num2} is {result}")
else:
print(result)

Output:

$ python script.py 5 10 --verbose
The result of adding 5.0 and 10.0 is 15.0

$ python script.py 5 10
15.0
note

You can make optional arguments mandatory by adding required=True to the add_argument call, though this is generally discouraged in favor of positional arguments.

Method 3: Accepting Lists of Values (nargs)

Sometimes "adding multiple arguments" means accepting a variable list of values for a single argument (e.g., processing a list of files). You can control this using the nargs parameter.

  • nargs='+': Gathers 1 or more values into a list.
  • nargs='*': Gathers 0 or more values into a list.
  • nargs=N: Gathers exactly N values.

Scenario: Processing Multiple Files

import argparse

parser = argparse.ArgumentParser()

# ⛔️ Incorrect: Defining separate arguments for an unknown number of files
# parser.add_argument("file1")
# parser.add_argument("file2")

# ✅ Correct: Use nargs='+' to accept a list into one variable
parser.add_argument("-f", "--files", nargs='+', required=True, help="List of files to process")

args = parser.parse_args()

print(f"Processing {len(args.files)} files:")
for filename in args.files:
print(f"- {filename}")

Output:

$ python script.py --files file1.txt file2.txt file3.txt
Processing 3 files:
- file1.txt
- file2.txt
- file3.txt
tip

When using nargs='+' with positional arguments, be careful not to create ambiguity. It is often safer to use nargs with optional flags (like --files above) so argparse knows exactly when the list ends.

Conclusion

To add multiple arguments in Python:

  1. Instantiate the ArgumentParser once.
  2. Call parser.add_argument() sequentially for every input you need.
  3. Distinguish between positional (mandatory, ordered) and optional (flags, unordered) inputs.
  4. Use nargs if a single argument needs to accept multiple values.