0
0
PythonHow-ToBeginner · 3 min read

How to Use argparse in Python: Simple Command-Line Parsing

Use the argparse module in Python to handle command-line arguments by creating an ArgumentParser object, adding arguments with add_argument(), and then parsing them with parse_args(). This lets your program accept inputs from the command line in a clean and user-friendly way.
📐

Syntax

The basic syntax to use argparse involves creating a parser, adding arguments, and parsing them:

  • ArgumentParser(): Creates a new parser object.
  • add_argument(): Defines what command-line arguments the program accepts.
  • parse_args(): Reads the arguments passed when running the script.
python
import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)')

args = parser.parse_args()
💻

Example

This example shows a program that takes integers from the command line and either sums them or finds the maximum, depending on the option used.

python
import argparse

parser = argparse.ArgumentParser(description='Sum or find max of integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+', help='integers to process')
parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find max)')

args = parser.parse_args()
print(args.accumulate(args.integers))
Output
If run as: python script.py 1 2 3 4 Output: 4 If run as: python script.py 1 2 3 4 --sum Output: 10
⚠️

Common Pitfalls

Common mistakes when using argparse include:

  • Not calling parse_args() before accessing arguments.
  • Using positional arguments incorrectly (forgetting to specify nargs for multiple values).
  • Confusing action='store_const' with other actions.
  • Not providing helpful help messages for arguments.

Example of a wrong and right way:

python
import argparse

# Wrong: forgetting to parse args
parser = argparse.ArgumentParser()
parser.add_argument('--name')
# print(args.name)  # This will cause an error because args is not defined

# Right:
args = parser.parse_args()
print(args.name)
📊

Quick Reference

ArgumentParser MethodPurpose
ArgumentParser()Create a new parser object
add_argument()Define a command-line argument
parse_args()Parse the arguments passed to the script
descriptionText shown in help describing the program
helpText shown in help describing an argument
actionDefines how to handle the argument (e.g., store, store_const)
nargsNumber of arguments expected (e.g., '+', '*', '?')
typeType to convert argument to (e.g., int, str)
defaultDefault value if argument is not provided

Key Takeaways

Use argparse.ArgumentParser() to start parsing command-line arguments.
Add arguments with add_argument() specifying name, type, and help text.
Call parse_args() to get the arguments passed when running the script.
Provide clear help messages to make your program user-friendly.
Watch out for common mistakes like forgetting to parse arguments before use.