Command-Line Arguments in Python: A Powerful Guide

Command-line arguments are extra bits of information you can provide to your Python scripts when you run them from the terminal. They make your scripts more flexible and user-friendly by allowing users to customize the behavior or input data. This guide will teach you how to harness the power of command-line arguments using Python’s argparse module.

1. Why Use Command-Line Arguments?

  • Flexibility: Allow users to customize the behavior of your script.
  • User-friendliness: Make your scripts easier to use by accepting input directly from the command line.
  • Automation: Enable integration with other tools and scripts via command-line parameters.

2. Argument Types: Options vs. Positional Arguments

  • Options (Flags): These arguments are typically preceded by a single dash (-) or double dash (--). They often represent on/off switches or modify the script’s behavior (e.g., -h for help, --verbose for detailed output).
  • Positional Arguments: These are required arguments that must be provided in a specific order. They usually represent filenames, data values, or other inputs.

3. The argparse Module: Your Command-Line Toolbox

The argparse module simplifies the process of defining and parsing command-line arguments.

from argparse import ArgumentParser

parser = ArgumentParser()

This creates an ArgumentParser object, which will manage your arguments.

4. Adding Arguments with add_argument()

Use add_argument() to define each argument:

parser.add_argument('--output', '-o', required=True, help='Destination file for output')
parser.add_argument('--text', '-t', required=True, help='Text to write to the file')
  • --output, -o: Specifies two ways to provide the argument (long and short forms).
  • required=True: Makes the argument mandatory.
  • help: Provides a brief description of the argument for the user.

5. Parsing Arguments with parse_args()

args = parser.parse_args()

This line parses the command-line arguments and returns an object (args) with attributes corresponding to the defined arguments. You can access their values using args.output and args.text.

6. Using Arguments in Your Script

with open(args.output, 'w') as f:
f.write(args.text + '\n')

print(f"Wrote '{args.text}' to file '{args.output}'")


Here, we write the text to the specified output file.