On this page
  1. optparse
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Migrating optparse to argparse
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects
  10. Constants & Attributes

optparse

Prev: operator | Up: stdlib_module | Next: os
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — optparse
Tags: #public #python3 #stdlib


Import

import optparse

Overview

Deprecated command-line option parser (OptionParser), superseded by argparse since Python 3.2. You'll still encounter optparse in legacy scripts and older build tools; use this page to read or maintain existing optparse code, and choose argparse for anything new.

Quick Start

import optparse

parser = optparse.OptionParser(usage="usage: %prog [options] file")
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False)
parser.add_option("-n", "--count", type="int", default=1)

options, args = parser.parse_args(["-v", "-n", "3", "data.txt"])
assert options.verbose is True and options.count == 3 and args == ["data.txt"]

Implementation Walkthrough

1. Migrating optparse to argparse

optparse returns (options, positional_args) separately, whereas argparse unifies options and positional arguments on a single Namespace:

# optparse:
#   parser.add_option("-o", "--output", dest="output", default="out.txt")
#   opts, args = parser.parse_args()
#
# argparse equivalent:
#   parser.add_argument("-o", "--output", default="out.txt")
#   parser.add_argument("files", nargs="*")
#   args = parser.parse_args()

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes