Python Basics: Parse Compact Option Lists with getopt
A small compatibility script may need conventional short and long options without a larger command-line interface. Python’s getopt separates options from operands while leaving value conversion to the caller. The fixture uses explicit argument lists so every result is reproducible.
Prepare a scratch directory
Tested on Linux with CPython 3.12.14. You need the named runtime, Bash, a text editor, and the standard mktemp, rm, and rmdir utilities. Run Python without -O so the assertions remain enabled. Any generated fixture files live inside an automatically cleaned temporary directory.
Keep using the same terminal. Stop if setup fails, before saving the source:
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save this as demonstrate-getopt.py:
import getopt
options, operands = getopt.getopt(
["-v", "--count=3", "input.txt"], "vc:", ["count="])
verbose = False
count = 1
for name, value in options:
if name == "-v":
verbose = True
elif name in ("-c", "--count"):
count = int(value)
assert count == 3 and verbose
assert operands == ["input.txt"]
print("Verbose:", verbose)
print("Count:", count)
print("Operands:", operands)
stopped, rest = getopt.getopt(["input.txt", "-v"], "v")
assert stopped == [] and rest == ["input.txt", "-v"]
print("After first operand:", rest)
_, literal = getopt.getopt(["--", "-v"], "v")
assert literal == ["-v"]
print("After option terminator:", literal)
try:
getopt.getopt(["--unknown"], "v", ["count="])
except getopt.GetoptError as error:
assert error.opt == "unknown"
print("Unknown option: rejected")
else:
raise AssertionError("Unknown option accepted")Run it:
python3 -B demonstrate-getopt.pyObserved output:
Verbose: True
Count: 3
Operands: ['input.txt']
After first operand: ['input.txt', '-v']
After option terminator: ['-v']
Unknown option: rejectedRead the result
A colon after c and an equals sign after count declare required option arguments. Parsed values remain strings, so the program explicitly converts the count. Ordinary getopt stops at the first non-option operand. A standalone -- ends option processing even when the next operand begins with a hyphen.
Apply it carefully
For a larger new CLI, argparse usually provides better help, validation, and error reporting. getopt does not automatically enforce numeric ranges, reject duplicate options, or choose a duplicate-value policy. gnu_getopt has different scanning behavior; do not substitute it without checking the intended operand rules and environment. Catch conversion errors separately from option-syntax errors in a real command-line entry point.
The official reference describes the API and its options.
Clean up
Remove the source and then the empty practice directory:
rm -- demonstrate-getopt.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirIf the directory is not empty, inspect the remaining files rather than deleting unknown contents.
Acknowledgements
This post was created with assistance from AI.