getopt
The Python getopt module parses command line options from sys.argv following Unix getopt() conventions.
The CPython documentation lists getopt under Superseded Modules and considers it feature complete, so new command line parameter processing features land in argparse or in third-party libraries rather than here. There’s no deprecation notice, though, so scripts that rely on Unix getopt() conventions can keep using it.
getopt processes short options like -v, -o filename, and long options like --verbose, --output=filename. It returns a list of recognized option-value pairs alongside any remaining non-option arguments:
>>> import getopt
>>> opts, args = getopt.getopt("-a -b -cfoo -d bar a1 a2".split(), "abc:d:")
>>> opts
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']
Key Features
- Parses short options from a compact string of letters like
"abc:d:" - Parses long options from a list of strings like
["output=", "verbose"] - Stops processing at the first non-option argument with
getopt()(Unix-style behavior) - Allows options to be intermixed with non-option arguments using
gnu_getopt()(GNU-style) - Returns options and non-option arguments in their original order with
gnu_getopt(), as of Python 3.14, when the short options string starts with-, inserting(None, [non_options])pairs inline - Returns a list of
(option, value)pairs and a list of remaining positional arguments - Supports options requiring an argument (
:/=) and, as of Python 3.14, optional arguments with::for short options and=?for long options
Frequently Used Classes and Functions
| Object | Type | Description |
|---|---|---|
getopt.getopt() |
Function | Parses options Unix-style, stopping at the first non-option argument |
getopt.gnu_getopt() |
Function | Parses options GNU-style, allowing options and non-option arguments to be intermixed |
getopt.GetoptError |
Exception | Raised when an unrecognized option or a missing required argument is encountered |
Examples
Parsing both short and long options from a simulated argument list:
>>> import getopt
>>> args = "--output=result.txt --verbose -n 5 file.txt".split()
>>> opts, rest = getopt.getopt(args, "n:", ["output=", "verbose"])
>>> opts
[('--output', 'result.txt'), ('--verbose', ''), ('-n', '5')]
>>> rest
['file.txt']
Catching GetoptError when an unrecognized option is passed:
>>> import getopt
>>> try:
... getopt.getopt(["-z"], "ab")
... except getopt.GetoptError as err:
... print(err)
option -z not recognized
Common Use Cases
The most common tasks for getopt include:
- Parsing command line flags and options in scripts that follow Unix conventions
- Supporting both short (
-o) and long (--output) forms of the same option - Collecting positional arguments that remain after option processing
- Porting or maintaining scripts originally written using C
getopt()idioms
Real-World Example
A typical script uses getopt() to parse a help flag, a verbose flag, and an output file option, then processes the remaining positional arguments:
tool.py
import getopt
import sys
def usage():
print("Usage: tool.py [-h] [-v] [-o OUTPUT] FILE [FILE ...]")
def main():
try:
opts, files = getopt.getopt(
sys.argv[1:], "hvo:", ["help", "verbose", "output="]
)
except getopt.GetoptError as err:
print(err)
usage()
sys.exit(2)
output = None
verbose = False
for opt, val in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-v", "--verbose"):
verbose = True
elif opt in ("-o", "--output"):
output = val
if verbose:
print(f"Processing {len(files)} file(s), output: {output or 'stdout'}")
for filename in files:
print(f"Processing {filename}")
if __name__ == "__main__":
main()
Run it with short or long option forms interchangeably:
$ python tool.py -v -o result.txt file1.txt file2.txt
Processing 2 file(s), output: result.txt
Processing file1.txt
Processing file2.txt
$ python tool.py --verbose --output=result.txt file1.txt
Processing 1 file(s), output: result.txt
Processing file1.txt
The opts list preserves the order in which options appear, and unrecognized options raise GetoptError with a descriptive message.
Related Resources
Tutorial
Python Command-Line Arguments
Python command-line arguments are the key to converting your programs into useful and enticing tools that are ready to be used in the terminal of your operating system. In this step-by-step tutorial, you'll learn their origins, standards, and basics, and how to implement them in your program.
For additional information on related topics, take a look at the following resources:
- Build Command-Line Interfaces With Python's argparse (Tutorial)
- Building Command Line Interfaces With argparse (Course)
- Click and Python: Build Extensible and Composable CLI Apps (Tutorial)
- 4 Techniques for Testing Python Command-Line (CLI) Apps (Tutorial)
- Command Line Interfaces in Python (Course)
- Build Command-Line Interfaces With Python's argparse (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Sept. 23, 2026