Python argparse Module

The argparse module in Python provides a way to handle command-line arguments passed to a script. It allows you to define the arguments your program requires, handle default values, and generate help messages for users.

Table of Contents

  1. Introduction
  2. Key Classes and Methods
    • ArgumentParser
    • add_argument
    • parse_args
    • print_help
    • print_usage
  3. Examples
    • Basic Example
    • Handling Different Argument Types
    • Using Optional Arguments
    • Generating Help Messages
    • Parsing Multiple Arguments
  4. Real-World Use Case
  5. Conclusion
  6. References

Introduction

The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.

Key Classes and Methods

ArgumentParser

The ArgumentParser class is used to create a new argument parser object.

import argparse

parser = argparse.ArgumentParser(description="Example argument parser")

add_argument

Defines how a single command-line argument should be parsed.

parser.add_argument('name', type=str, help='Name of the user')

parse_args

Parses the command-line arguments.

args = parser.parse_args()
print(f'Hello, {args.name}!')

print_help

Prints a help message.

parser.print_help()

print_usage

Prints a usage message.

parser.print_usage()

Examples

Basic Example

import argparse

parser = argparse.ArgumentParser(description="Greet the user")
parser.add_argument('name', type=str, help='Name of the user')

args = parser.parse_args()
print(f'Hello, {args.name}!')

Command Line:

$ python script.py Alice

Output:

Hello, Alice!

Handling Different Argument Types

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()
print(args.accumulate(args.integers))

Command Line:

$ python script.py 1 2 3 4 --sum

Output:

10

Using Optional Arguments

import argparse

parser = argparse.ArgumentParser(description="Greet the user")
parser.add_argument('--name', type=str, help='Name of the user', default='World')

args = parser.parse_args()
print(f'Hello, {args.name}!')

Command Line:

$ python script.py

Output:

Hello, World!

Generating Help Messages

import argparse

parser = argparse.ArgumentParser(description="Example argument parser")
parser.add_argument('name', type=str, help='Name of the user')
parser.add_argument('--age', type=int, help='Age of the user')

args = parser.parse_args()
print(f'Name: {args.name}')
print(f'Age: {args.age}')

Command Line:

$ python script.py --help

Output:

usage: script.py [-h] [--age AGE] name

Example argument parser

positional arguments:
  name        Name of the user

optional arguments:
  -h, --help  show this help message and exit
  --age AGE   Age of the user

Parsing Multiple Arguments

import argparse

parser = argparse.ArgumentParser(description="Sum or multiply integers.")
parser.add_argument('integers', metavar='N', type=int, nargs='+', help='integers to be processed')
parser.add_argument('--operation', choices=['sum', 'mul'], default='sum', help='operation to be performed (default: sum)')

args = parser.parse_args()

if args.operation == 'sum':
    result = sum(args.integers)
else:
    result = 1
    for x in args.integers:
        result *= x

print(f'Result: {result}')

Command Line:

$ python script.py 1 2 3 4 --operation mul

Output:

Result: 24

Real-World Use Case

Backup Script

import argparse
import os
import shutil

def backup_files(source, destination):
    if not os.path.exists(destination):
        os.makedirs(destination)
    for filename in os.listdir(source):
        file_path = os.path.join(source, filename)
        if os.path.isfile(file_path):
            shutil.copy(file_path, destination)

parser = argparse.ArgumentParser(description="Backup files from source to destination.")
parser.add_argument('source', type=str, help='Source directory')
parser.add_argument('destination', type=str, help='Destination directory')

args = parser.parse_args()
backup_files(args.source, args.destination)
print(f'Files from {args.source} have been backed up to {args.destination}')

Command Line:

$ python backup.py /path/to/source /path/to/destination

Output:

Files from /path/to/source have been backed up to /path/to/destination

Conclusion

The argparse module in Python provides a robust and user-friendly way to handle command-line arguments. By defining the expected arguments and their types, it simplifies the process of parsing and validating user input, and it automatically generates helpful messages. This makes it used for building command-line interfaces in Python.

References

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top