On this page
  1. getopt
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. getopt() vs. gnu_getopt()
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects

getopt

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


Import

import getopt

Overview

C-style command-line option parser (getopt(), gnu_getopt()) mirroring the POSIX C getopt(3) function. Use getopt only when maintaining legacy scripts or porting a C CLI tool whose flag-parsing behavior must match getopt(3) verbatim; for new Python CLIs, use argparse.

Quick Start

import getopt

argv = ["-v", "-o", "out.txt", "input.txt"]
opts, args = getopt.getopt(argv, "vo:", ["verbose", "output="])
assert opts == [("-v", ""), ("-o", "out.txt")]
assert args == ["input.txt"]

Implementation Walkthrough

1. getopt() vs. gnu_getopt()

Standard getopt() stops parsing options at the first non-option positional argument, while gnu_getopt() allows options and positional arguments to be intermixed:

import getopt

opts, args = getopt.gnu_getopt(["input.txt", "--output=out.txt"], "o:", ["output="])
assert opts == [("--output", "out.txt")]
assert args == ["input.txt"]

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes