DEV Community

Nadun Udaraka
Nadun Udaraka

Posted on

Python "argparse" library

Introduction to "argparse"

The argparse module, included in the Python standard library (since versions 2.7 and 3.2), is a powerful tool for creating user-friendly command-line interfaces (CLIs) for your Python scripts. It simplifies the process of parsing arguments passed from the command line, making your scripts more robust and easier to use.

Key Features:

  • Flexibility: Defines various argument types (positional, optional, flags) and allows for multiple values.
  • Error Handling: Catches invalid arguments and provides informative error messages.
  • Help Messages: Generates usage and help messages automatically based on argument definitions.
  • Subparsers: Enables creating complex CLIs with hierarchical structures.

Step by step Tutorial:

1 . Import the module:

import argparse
Enter fullscreen mode Exit fullscreen mode

2 . Create an Argument Parser:

parser = argparse.ArgumentParser(description='Your script description')
Enter fullscreen mode Exit fullscreen mode



3 . Define Arguments:
Positional arguments: Required arguments that appear in a specific order after the script name.

parser.add_argument('filename', help='The file to process')
Enter fullscreen mode Exit fullscreen mode

Optional arguments: Added using flags (preceded by - or --) and can have default values.

parser.add_argument('-v', '--verbose', action='store_true', default=False,
                    help='Print verbose output')
parser.add_argument('-o', '--output', default='output.txt',
                    help='Output file (default: output.txt)')
Enter fullscreen mode Exit fullscreen mode
  • action='store_true': Sets a boolean flag (True if present, False otherwise).
  • default='value': Provides a default value if the argument is not specified. Argument types: Control how arguments are interpreted. parser.add_argument('--age', type=int, help='Your age (as an integer)') parser.add_argument('--repeat', type=float, nargs=2, help='Repeat a value (takes two floating-point numbers)')
  • type=int: Converts the argument value to an integer.
  • nargs=2: Allows capturing multiple values for the argument. 4 . Parse Arguments:
args = parser.parse_args()
Enter fullscreen mode Exit fullscreen mode

This captures the parsed arguments into a namespace object (args) that you can access in your script.


5 . Use the Arguments:

if args.verbose:
    print('Verbose mode enabled')

with open(args.filename, 'r') as f:
    # Process the file contents

if args.output:
    with open(args.output, 'w') as f:
        # Write output to the specified file
Enter fullscreen mode Exit fullscreen mode

Complete Example:


import argparse

parser = argparse.ArgumentParser(description='Count lines in a file')
parser.add_argument('filename', help='The file to process')
parser.add_argument('-v', '--verbose', action='store_true', default=False,
                    help='Print detailed information')

args = parser.parse_args()

if args.verbose:
    print('Counting lines in:', args.filename)

with open(args.filename, 'r') as f:
    num_lines = sum(1 for _ in f)

print(f'The file {args.filename} has {num_lines} lines.')
Enter fullscreen mode Exit fullscreen mode

Tips:

  • Customize help messages using help arguments in add_argument
  • Group related arguments using parser.add_argument_group()
  • Create subparsers for complex CLIs with multiple commands using subparsers_action='store_subcommand'

By following these steps and exploring the advanced features of argparse, you can create robust, user-friendly, and well-documented command-line interfaces for your Python scripts.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs