0
0
PythonHow-ToBeginner · 3 min read

How to Add Positional Arguments in Argparse in Python

To add positional arguments in argparse, use the add_argument method without a leading dash in the argument name. These arguments are required and are identified by their position in the command line input.
📐

Syntax

Use parser.add_argument('name') to add a positional argument where 'name' is the argument's identifier. Positional arguments do not start with dashes and are required by default.

  • parser: an instance of ArgumentParser
  • add_argument: method to add an argument
  • 'name': the name of the positional argument
python
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('filename')  # positional argument
args = parser.parse_args()
print(f"File to process: {args.filename}")
💻

Example

This example shows how to add two positional arguments: input_file and output_file. The program prints both values provided by the user.

python
import argparse

parser = argparse.ArgumentParser(description='Process input and output files.')
parser.add_argument('input_file', help='Input file path')
parser.add_argument('output_file', help='Output file path')

args = parser.parse_args()
print(f"Input file: {args.input_file}")
print(f"Output file: {args.output_file}")
Output
Input file: data.txt Output file: result.txt
⚠️

Common Pitfalls

Common mistakes include:

  • Using dashes (e.g., '--file') which creates optional arguments, not positional.
  • Not providing required positional arguments when running the script, causing errors.
  • Confusing the order of positional arguments since their position matters.

Example of wrong and right usage:

python
# Wrong: creates optional argument
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--file')  # This is optional

# Right: positional argument
parser.add_argument('file')  # This is required and positional
📊

Quick Reference

Summary tips for positional arguments in argparse:

  • Positional arguments are added without dashes.
  • They are required by default.
  • Order matters: the first positional argument corresponds to the first input value.
  • Use help to describe each argument.

Key Takeaways

Add positional arguments in argparse by calling add_argument with a name that has no dashes.
Positional arguments are required and their order in the command line matters.
Avoid using dashes for positional arguments to prevent them from becoming optional.
Always provide help text to explain what each positional argument does.
If you omit a positional argument when running the script, argparse will show an error.