Python’s optparse module parses --flag and -f style options — it is the predecessor to argparse and is still found in older codebases. import optparse. Create: parser = optparse.OptionParser(usage="%prog [options] arg", description="..."). Add option: parser.add_option("-v", "--verbose", action="store_true", default=False, dest="verbose", help="enable verbose output"). Parse: (options, args) = parser.parse_args() — options is a Values namespace; args is the list of non-option arguments. Actions: store (default), store_true, store_false, store_const, append, count, callback. Types: "string" (default), "int", "float", "long", "complex", "choice". Groups: grp = optparse.OptionGroup(parser, "Advanced") + grp.add_option(...) + parser.add_option_group(grp). Defaults: parser.set_defaults(output="out.txt"). Error: parser.error("message") prints to stderr and exits 2. Help: parser.format_help(). Note: optparse is deprecated since Python 3.2 — prefer argparse for new code. Claude Code generates maintenance scripts, legacy CLI tools, migration helpers, and backward-compatible option parsers.
CLAUDE.md for optparse
## optparse Stack
- Stdlib: import optparse
- Create: parser = optparse.OptionParser(usage="%prog [opts] arg")
- Add: parser.add_option("-v","--verbose", action="store_true", default=False)
- Parse: opts, args = parser.parse_args() # opts.verbose, args[0]
- Error: parser.error("bad input") # exit 2
- Help: parser.format_help()
- Note: DEPRECATED since Python 3.2 — use argparse for new code
optparse CLI Pipeline
# app/optparseutil.py — builder, validator, help, migrator, legacy runner
from __future__ import annotations
import optparse
import os
import sys
from dataclasses import dataclass, field
from typing import Any
# ─────────────────────────────────────────────────────────────────────────────
# 1. Builder helper
# ─────────────────────────────────────────────────────────────────────────────
def make_parser(
usage: str = "%prog [options]",
description: str = "",
epilog: str = "",
version: "str | None" = None,
) -> optparse.OptionParser:
"""
Create a configured OptionParser with standard defaults.
Example:
parser = make_parser(
usage="%prog [options] FILE",
description="Process a file.",
version="1.0",
)
parser.add_option("-v", "--verbose", action="store_true", default=False)
opts, args = parser.parse_args()
"""
kwargs: dict[str, Any] = dict(
usage=usage,
description=description,
epilog=epilog,
)
if version:
kwargs["version"] = version
return optparse.OptionParser(**kwargs)
# ─────────────────────────────────────────────────────────────────────────────
# 2. Typed option factories
# ─────────────────────────────────────────────────────────────────────────────
def add_flag(
parser: optparse.OptionParser,
short: str,
long: str,
dest: "str | None" = None,
default: bool = False,
help: str = "",
) -> None:
"""
Add a boolean flag (--flag / --no-flag pattern).
Example:
add_flag(parser, "-v", "--verbose", help="print extra output")
add_flag(parser, "-q", "--quiet", help="suppress output", default=False)
"""
parser.add_option(
short, long,
action="store_true",
dest=dest or long.lstrip("-").replace("-", "_"),
default=default,
help=help,
)
def add_string_option(
parser: optparse.OptionParser,
short: str,
long: str,
default: "str | None" = None,
metavar: str = "VALUE",
help: str = "",
) -> None:
"""
Add a string-valued option.
Example:
add_string_option(parser, "-o", "--output", default="out.txt",
metavar="FILE", help="output file path")
"""
parser.add_option(
short, long,
type="string",
default=default,
metavar=metavar,
help=help,
)
def add_int_option(
parser: optparse.OptionParser,
short: str,
long: str,
default: int = 0,
metavar: str = "N",
help: str = "",
) -> None:
"""
Add an integer option.
Example:
add_int_option(parser, "-n", "--count", default=10, help="repeat count")
"""
parser.add_option(
short, long,
type="int",
default=default,
metavar=metavar,
help=help,
)
def add_choice_option(
parser: optparse.OptionParser,
short: str,
long: str,
choices: list[str],
default: "str | None" = None,
help: str = "",
) -> None:
"""
Add an option restricted to a predefined set of choices.
Example:
add_choice_option(parser, "-l", "--level",
choices=["debug","info","warn","error"],
default="info", help="log level")
"""
parser.add_option(
short, long,
type="choice",
choices=choices,
default=default,
help=help + f" (choices: {', '.join(choices)})",
)
def add_append_option(
parser: optparse.OptionParser,
short: str,
long: str,
metavar: str = "VALUE",
help: str = "",
) -> None:
"""
Add an option that can be specified multiple times (appends to a list).
Example:
add_append_option(parser, "-i", "--include", metavar="PATTERN",
help="include pattern (can repeat)")
# --include "*.py" --include "*.md" → opts.include = ["*.py","*.md"]
"""
parser.add_option(
short, long,
action="append",
metavar=metavar,
help=help,
)
# ─────────────────────────────────────────────────────────────────────────────
# 3. Parsed options validator
# ─────────────────────────────────────────────────────────────────────────────
@dataclass
class ParsedCLI:
"""
Structured wrapper around optparse.parse_args() output.
Example:
cli = ParsedCLI.from_parser(parser)
if not cli.ok:
print(cli.errors)
else:
print(cli.opts.output, cli.args)
"""
opts: optparse.Values
args: list[str]
errors: list[str] = field(default_factory=list)
@classmethod
def from_argv(
cls,
parser: optparse.OptionParser,
argv: "list[str] | None" = None,
) -> "ParsedCLI":
try:
opts, args = parser.parse_args(argv)
return cls(opts=opts, args=args)
except SystemExit:
return cls(opts=optparse.Values(), args=[], errors=["parse failed"])
@property
def ok(self) -> bool:
return not self.errors
def require_args(
self,
parser: optparse.OptionParser,
min_args: int,
max_args: "int | None" = None,
) -> "ParsedCLI":
"""Validate positional argument count in-place."""
n = len(self.args)
if n < min_args:
self.errors.append(f"expected at least {min_args} argument(s), got {n}")
parser.print_help()
if max_args is not None and n > max_args:
self.errors.append(f"expected at most {max_args} argument(s), got {n}")
return self
def require_file(self, path_attr: str) -> "ParsedCLI":
"""Validate that the option named path_attr points to an existing file."""
p = getattr(self.opts, path_attr, None)
if p and not os.path.isfile(p):
self.errors.append(f"file not found: {p!r}")
return self
# ─────────────────────────────────────────────────────────────────────────────
# 4. argparse migration helper
# ─────────────────────────────────────────────────────────────────────────────
def opts_to_dict(opts: optparse.Values) -> dict[str, Any]:
"""
Convert an optparse Values namespace to a plain dict.
Useful when migrating to argparse or passing to libraries expecting dicts.
Example:
d = opts_to_dict(opts)
print(d)
"""
return vars(opts)
def describe_parser(parser: optparse.OptionParser) -> list[dict]:
"""
Describe all registered options as a list of dicts.
Useful for generating argparse equivalents.
Example:
for opt_info in describe_parser(parser):
print(opt_info)
"""
result = []
for opt in parser.option_list:
if opt.dest is None:
continue
result.append({
"opts": opt._short_opts + opt._long_opts,
"dest": opt.dest,
"action": opt.action,
"type": opt.type,
"default": opt.default,
"help": opt.help,
})
return result
# ─────────────────────────────────────────────────────────────────────────────
# 5. Complete CLI application example
# ─────────────────────────────────────────────────────────────────────────────
def build_demo_parser() -> optparse.OptionParser:
"""
Build a representative demo OptionParser for testing.
Example:
parser = build_demo_parser()
opts, args = parser.parse_args(["--verbose", "input.txt"])
"""
parser = make_parser(
usage="%prog [options] INPUT",
description="Demo optparse CLI.",
version="1.0",
)
# Core options
add_flag(parser, "-v", "--verbose", help="verbose output")
add_flag(parser, "-d", "--dry-run", help="dry run — no writes")
add_string_option(parser, "-o", "--output", default="-",
metavar="FILE", help="output file (default: stdout)")
add_int_option(parser, "-n", "--count", default=10,
help="max items to process")
add_choice_option(parser, "-f", "--format",
choices=["text", "json", "csv"],
default="text", help="output format")
# Advanced group
grp = optparse.OptionGroup(parser, "Advanced",
"Options for power users.")
grp.add_option("--timeout", type="int", default=30,
help="timeout in seconds (default: 30)")
grp.add_option("--retries", type="int", default=3,
help="retry count (default: 3)")
add_append_option(grp, "-e", "--exclude",
metavar="PATTERN", help="exclude pattern (repeatable)")
parser.add_option_group(grp)
return parser
# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
print("=== optparse demo ===")
parser = build_demo_parser()
# ── print_help ────────────────────────────────────────────────────────────
print("\n--- format_help ---")
print(parser.format_help())
# ── parse simple argv ─────────────────────────────────────────────────────
print("\n--- parse_args ---")
opts, args = parser.parse_args(
["-v", "-n", "5", "--format", "json", "--exclude", "*.log",
"--exclude", "*.tmp", "myfile.txt"]
)
print(f" verbose = {opts.verbose}")
print(f" count = {opts.count}")
print(f" format = {opts.format}")
print(f" output = {opts.output}")
print(f" exclude = {opts.exclude}")
print(f" timeout = {opts.timeout}")
print(f" args = {args}")
# ── opts_to_dict ──────────────────────────────────────────────────────────
print("\n--- opts_to_dict ---")
d = opts_to_dict(opts)
for k, v in sorted(d.items()):
print(f" {k}: {v!r}")
# ── describe_parser ───────────────────────────────────────────────────────
print("\n--- describe_parser ---")
for opt_info in describe_parser(parser):
print(f" {opt_info['opts']} dest={opt_info['dest']!r} "
f"type={opt_info['type']} default={opt_info['default']!r}")
# ── ParsedCLI.from_argv ────────────────────────────────────────────────────
print("\n--- ParsedCLI.from_argv ---")
cli = ParsedCLI.from_argv(parser, ["--count", "3", "in.txt"])
cli.require_args(parser, min_args=1)
print(f" ok={cli.ok} count={cli.opts.count} args={cli.args}")
print("\n=== done ===")
For the argparse alternative — argparse is optparse’s official successor (Python 3.2+), adding subcommands, mutually exclusive groups, file type, nargs, */+ quantifiers, and better error messages — always use argparse for new code; use optparse only when maintaining existing scripts that depend on it or when migrating old code incrementally. For the click (PyPI) / typer (PyPI) alternative — click and typer (built on click) provide decorator-based CLI building with automatic type coercion, nested command groups, environment variable integration, and rich testing utilities — use these for new user-facing CLI tools where developer ergonomics matter; use optparse/argparse when you need zero dependencies or are working inside an environment where pip is unavailable. The Claude Skills 360 bundle includes optparse skill sets covering make_parser() factory, add_flag()/add_string_option()/add_int_option()/add_choice_option()/add_append_option() typed option factories, ParsedCLI.from_argv() with require_args()/require_file() validators, opts_to_dict() conversion, describe_parser() introspection, and build_demo_parser() with grouped options. Start with the free tier to try option parsing patterns and optparse pipeline code generation.