Skip to content

optparse

The Python optparse module provides a declarative parser for command-line options, giving scripts a way to describe their expected flags and arguments and then turn sys.argv into a populated options object and a list of positional arguments. It has been part of the standard library since Python 2.3 and predates argparse, which is now the recommended choice for new code.

Here’s a quick example that defines an option and parses a sample argument list:

Language: Python
>>> import optparse

>>> parser = optparse.OptionParser()
>>> parser.add_option("-f", "--file", dest="filename")
<Option at 0x...: -f/--file>
>>> options, args = parser.parse_args(["-f", "data.txt", "report"])
>>> options.filename
'data.txt'
>>> args
['report']

The optparse module is part of Python’s standard library, so no installation is required. Note that optparse is no longer under active development, and the official documentation recommends argparse for new projects.

Key Features

  • Declarative option definitions using add_option()
  • Built-in option types such as string, int, float, and choice
  • Automatic generation of usage and help messages
  • Configurable actions including store, store_true, store_false, append, and count
  • Support for option groups that organize related flags in the help output
  • Custom callbacks that run when an option is encountered
  • Error reporting that prints a usage message and exits the program

Frequently Used Classes and Functions

Object Type Description
optparse.OptionParser Class Represents the top-level command-line parser
optparse.Option Class Represents a single command-line option and its metadata
optparse.OptionGroup Class Groups related options together in help output
optparse.Values Class Holds the parsed option values as attributes
OptionParser.add_option() Method Registers a new option with the parser
OptionParser.parse_args() Method Parses a list of arguments and returns options and positionals
OptionParser.error() Method Prints a usage message and exits with an error status
optparse.OptionError Exception Signals an invalid option definition at setup time
optparse.OptionValueError Exception Signals an invalid value supplied on the command line

Examples

Define a boolean flag that flips a default-True value to False when the option is supplied:

Language: Python
>>> import optparse

>>> parser = optparse.OptionParser()
>>> parser.add_option(
...     "-q",
...     "--quiet",
...     action="store_false",
...     dest="verbose",
...     default=True
... )
<Option at 0x...: -q/--quiet>

>>> options, args = parser.parse_args(["-q"])
>>> options.verbose
False

Use a typed option with a restricted set of choices:

Language: Python
>>> import optparse

>>> parser = optparse.OptionParser()
>>> parser.add_option(
...     "-c",
...     "--color",
...     type="choice",
...     choices=["red", "green", "blue"]
... )
<Option at 0x...: -c/--color>

>>> options, args = parser.parse_args(["-c", "green"])
>>> options.color
'green'

Read an integer option with a default value:

Language: Python
>>> import optparse

>>> parser = optparse.OptionParser()
>>> parser.add_option(
...     "-n",
...     "--lines",
...     type="int",
...     default=10
... )
<Option at 0x...: -n/--lines>

>>> options, args = parser.parse_args(["-n", "25"])
>>> options.lines
25

Common Use Cases

The most common tasks for optparse include:

  • Maintaining legacy command-line tools that already depend on optparse
  • Building scripts that need precise control over how options and positional arguments are interleaved
  • Parsing options whose values may begin with a dash, such as flags forwarded to a subprocess
  • Providing a lower-level foundation for third-party argument parsing libraries
  • Porting existing code incrementally before migrating to argparse

Real-World Example

Consider a small script that counts lines in a file, with flags for the input path and verbose output:

Language: Python Filename: count_lines.py
import optparse

def parse_args():
    parser = optparse.OptionParser(
        usage="usage: %prog [options] -f FILE"
    )
    parser.add_option(
        "-f",
        "--file",
        dest="filename",
        help="input file to read",
        metavar="FILE",
    )
    parser.add_option(
        "-v",
        "--verbose",
        action="store_true",
        dest="verbose",
        default=False,
        help="print extra diagnostic output",
    )
    options, _ = parser.parse_args()

    if options.filename is None:
        parser.error("the -f/--file option is required")

    return options

def main():
    options = parse_args()

    with open(options.filename) as source:
        count = sum(1 for _ in source)

    if options.verbose:
        print(f"Counted {count} lines in {options.filename}")
    else:
        print(count)

if __name__ == "__main__":
    main()

Run it on the command line:

Language: Shell
$ python count_lines.py -f data.txt -v
Counted 42 lines in data.txt

Splitting parse_args() from main() keeps the option-handling logic separate from the line-counting work. The parser validates the flags, reports a friendly error when -f is missing, and exposes the parsed values as attributes on the options object that main() can then consume.

Tutorial

Build Command-Line Interfaces With Python's argparse

In this step-by-step Python tutorial, you'll learn how to take your command-line Python scripts to the next level by adding a convenient command-line interface (CLI) that you can write with the argparse module from the standard library.

intermediate python stdlib

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated May 7, 2026