| 1 |
:mod:`!getopt` --- C-style parser for command line options |
| 2 |
========================================================== |
| 3 |
|
| 4 |
.. module:: getopt |
| 5 |
:synopsis: Portable parser for command line options; support both short and |
| 6 |
long option names. |
| 7 |
|
| 8 |
**Source code:** :source:`Lib/getopt.py` |
| 9 |
|
| 10 |
.. note:: |
| 11 |
|
| 12 |
This module is considered feature complete. A more declarative and |
| 13 |
extensible alternative to this API is provided in the :mod:`optparse` |
| 14 |
module. Further functional enhancements for command line parameter |
| 15 |
processing are provided either as third party modules on PyPI, |
| 16 |
or else as features in the :mod:`argparse` module. |
| 17 |
|
| 18 |
-------------- |
| 19 |
|
| 20 |
This module helps scripts to parse the command line arguments in ``sys.argv``. |
| 21 |
It supports the same conventions as the Unix :c:func:`!getopt` function (including |
| 22 |
the special meanings of arguments of the form '``-``' and '``--``'). Long |
| 23 |
options similar to those supported by GNU software may be used as well via an |
| 24 |
optional third argument. |
| 25 |
|
| 26 |
Users who are unfamiliar with the Unix :c:func:`!getopt` function should consider |
| 27 |
using the :mod:`argparse` module instead. Users who are familiar with the Unix |
| 28 |
:c:func:`!getopt` function, but would like to get equivalent behavior while |
| 29 |
writing less code and getting better help and error messages should consider |
| 30 |
using the :mod:`optparse` module. See :ref:`choosing-an-argument-parser` for |
| 31 |
additional details. |
| 32 |
|
| 33 |
This module provides two functions and an |
| 34 |
exception: |
| 35 |
|
| 36 |
|
| 37 |
.. function:: getopt(args, shortopts, longopts=[]) |
| 38 |
|
| 39 |
Parses command line options and parameter list. *args* is the argument list to |
| 40 |
be parsed, without the leading reference to the running program. Typically, this |
| 41 |
means ``sys.argv[1:]``. *shortopts* is the string of option letters that the |
| 42 |
script wants to recognize, with options that require an argument followed by a |
| 43 |
colon (``':'``) and options that accept an optional argument followed by |
| 44 |
two colons (``'::'``); i.e., the same format that Unix :c:func:`!getopt` uses. |
| 45 |
|
| 46 |
.. note:: |
| 47 |
|
| 48 |
Unlike GNU :c:func:`!getopt`, after a non-option argument, all further |
| 49 |
arguments are considered also non-options. This is similar to the way |
| 50 |
non-GNU Unix systems work. |
| 51 |
|
| 52 |
*longopts*, if specified, must be a list of strings with the names of the |
| 53 |
long options which should be supported. The leading ``'--'`` characters |
| 54 |
should not be included in the option name. Long options which require an |
| 55 |
argument should be followed by an equal sign (``'='``). |
| 56 |
Long options which accept an optional argument should be followed by |
| 57 |
an equal sign and question mark (``'=?'``). |
| 58 |
To accept only long options, *shortopts* should be an |
| 59 |
empty string. Long options on the command line can be recognized so long as |
| 60 |
they provide a prefix of the option name that matches exactly one of the |
| 61 |
accepted options. For example, if *longopts* is ``['foo', 'frob']``, the |
| 62 |
option ``--fo`` will match as ``--foo``, but ``--f`` will |
| 63 |
not match uniquely, so :exc:`GetoptError` will be raised. |
| 64 |
|
| 65 |
The return value consists of two elements: the first is a list of ``(option, |
| 66 |
value)`` pairs; the second is the list of program arguments left after the |
| 67 |
option list was stripped (this is a trailing slice of *args*). Each |
| 68 |
option-and-value pair returned has the option as its first element, prefixed |
| 69 |
with a hyphen for short options (e.g., ``'-x'``) or two hyphens for long |
| 70 |
options (e.g., ``'--long-option'``), and the option argument as its |
| 71 |
second element, or an empty string if the option has no argument. The |
| 72 |
options occur in the list in the same order in which they were found, thus |
| 73 |
allowing multiple occurrences. Long and short options may be mixed. |
| 74 |
|
| 75 |
.. versionchanged:: 3.14 |
| 76 |
Optional arguments are supported. |
| 77 |
|
| 78 |
|
| 79 |
.. function:: gnu_getopt(args, shortopts, longopts=[]) |
| 80 |
|
| 81 |
This function works like :func:`getopt`, except that GNU style scanning mode is |
| 82 |
used by default. This means that option and non-option arguments may be |
| 83 |
intermixed. The :func:`getopt` function stops processing options as soon as a |
| 84 |
non-option argument is encountered. |
| 85 |
|
| 86 |
If the first character of the option string is ``'+'``, or if the environment |
| 87 |
variable :envvar:`!POSIXLY_CORRECT` is set, then option processing stops as |
| 88 |
soon as a non-option argument is encountered. |
| 89 |
|
| 90 |
If the first character of the option string is ``'-'``, non-option arguments |
| 91 |
that are followed by options are added to the list of option-and-value pairs |
| 92 |
as a pair that has ``None`` as its first element and the list of non-option |
| 93 |
arguments as its second element. |
| 94 |
The second element of the :func:`!gnu_getopt` result is a list of |
| 95 |
program arguments after the last option. |
| 96 |
|
| 97 |
.. versionchanged:: 3.14 |
| 98 |
Support for returning intermixed options and non-option arguments in order. |
| 99 |
|
| 100 |
|
| 101 |
.. exception:: GetoptError |
| 102 |
|
| 103 |
This is raised when an unrecognized option is found in the argument list or when |
| 104 |
an option requiring an argument is given none. The argument to the exception is |
| 105 |
a string indicating the cause of the error. For long options, an argument given |
| 106 |
to an option which does not require one will also cause this exception to be |
| 107 |
raised. The attributes :attr:`!msg` and :attr:`!opt` give the error message and |
| 108 |
related option; if there is no specific option to which the exception relates, |
| 109 |
:attr:`!opt` is an empty string. |
| 110 |
|
| 111 |
.. XXX deprecated? |
| 112 |
.. exception:: error |
| 113 |
|
| 114 |
Alias for :exc:`GetoptError`; for backward compatibility. |
| 115 |
|
| 116 |
An example using only Unix style options: |
| 117 |
|
| 118 |
.. doctest:: |
| 119 |
|
| 120 |
>>> import getopt |
| 121 |
>>> args = '-a -b -cfoo -d bar a1 a2'.split() |
| 122 |
>>> args |
| 123 |
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2'] |
| 124 |
>>> optlist, args = getopt.getopt(args, 'abc:d:') |
| 125 |
>>> optlist |
| 126 |
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')] |
| 127 |
>>> args |
| 128 |
['a1', 'a2'] |
| 129 |
|
| 130 |
Using long option names is equally easy: |
| 131 |
|
| 132 |
.. doctest:: |
| 133 |
|
| 134 |
>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2' |
| 135 |
>>> args = s.split() |
| 136 |
>>> args |
| 137 |
['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2'] |
| 138 |
>>> optlist, args = getopt.getopt(args, 'x', [ |
| 139 |
... 'condition=', 'output-file=', 'testing']) |
| 140 |
>>> optlist |
| 141 |
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')] |
| 142 |
>>> args |
| 143 |
['a1', 'a2'] |
| 144 |
|
| 145 |
Optional arguments should be specified explicitly: |
| 146 |
|
| 147 |
.. doctest:: |
| 148 |
|
| 149 |
>>> s = '-Con -C --color=off --color a1 a2' |
| 150 |
>>> args = s.split() |
| 151 |
>>> args |
| 152 |
['-Con', '-C', '--color=off', '--color', 'a1', 'a2'] |
| 153 |
>>> optlist, args = getopt.getopt(args, 'C::', ['color=?']) |
| 154 |
>>> optlist |
| 155 |
[('-C', 'on'), ('-C', ''), ('--color', 'off'), ('--color', '')] |
| 156 |
>>> args |
| 157 |
['a1', 'a2'] |
| 158 |
|
| 159 |
The order of options and non-option arguments can be preserved: |
| 160 |
|
| 161 |
.. doctest:: |
| 162 |
|
| 163 |
>>> s = 'a1 -x a2 a3 a4 --long a5 a6' |
| 164 |
>>> args = s.split() |
| 165 |
>>> args |
| 166 |
['a1', '-x', 'a2', 'a3', 'a4', '--long', 'a5', 'a6'] |
| 167 |
>>> optlist, args = getopt.gnu_getopt(args, '-x:', ['long=']) |
| 168 |
>>> optlist |
| 169 |
[(None, ['a1']), ('-x', 'a2'), (None, ['a3', 'a4']), ('--long', 'a5')] |
| 170 |
>>> args |
| 171 |
['a6'] |
| 172 |
|
| 173 |
In a script, typical usage is something like this: |
| 174 |
|
| 175 |
.. testcode:: |
| 176 |
|
| 177 |
import getopt, sys |
| 178 |
|
| 179 |
def main(): |
| 180 |
try: |
| 181 |
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="]) |
| 182 |
except getopt.GetoptError as err: |
| 183 |
# print help information and exit: |
| 184 |
print(err) # will print something like "option -a not recognized" |
| 185 |
usage() |
| 186 |
sys.exit(2) |
| 187 |
output = None |
| 188 |
verbose = False |
| 189 |
for o, a in opts: |
| 190 |
if o == "-v": |
| 191 |
verbose = True |
| 192 |
elif o in ("-h", "--help"): |
| 193 |
usage() |
| 194 |
sys.exit() |
| 195 |
elif o in ("-o", "--output"): |
| 196 |
output = a |
| 197 |
else: |
| 198 |
assert False, "unhandled option" |
| 199 |
process(args, output=output, verbose=verbose) |
| 200 |
|
| 201 |
if __name__ == "__main__": |
| 202 |
main() |
| 203 |
|
| 204 |
Note that an equivalent command line interface could be produced with less code |
| 205 |
and more informative help and error messages by using the :mod:`optparse` module: |
| 206 |
|
| 207 |
.. testcode:: |
| 208 |
|
| 209 |
import optparse |
| 210 |
|
| 211 |
if __name__ == '__main__': |
| 212 |
parser = optparse.OptionParser() |
| 213 |
parser.add_option('-o', '--output') |
| 214 |
parser.add_option('-v', dest='verbose', action='store_true') |
| 215 |
opts, args = parser.parse_args() |
| 216 |
process(args, output=opts.output, verbose=opts.verbose) |
| 217 |
|
| 218 |
A roughly equivalent command line interface for this case can also be |
| 219 |
produced by using the :mod:`argparse` module: |
| 220 |
|
| 221 |
.. testcode:: |
| 222 |
|
| 223 |
import argparse |
| 224 |
|
| 225 |
if __name__ == '__main__': |
| 226 |
parser = argparse.ArgumentParser() |
| 227 |
parser.add_argument('-o', '--output') |
| 228 |
parser.add_argument('-v', dest='verbose', action='store_true') |
| 229 |
parser.add_argument('rest', nargs='*') |
| 230 |
args = parser.parse_args() |
| 231 |
process(args.rest, output=args.output, verbose=args.verbose) |
| 232 |
|
| 233 |
See :ref:`choosing-an-argument-parser` for details on how the ``argparse`` |
| 234 |
version of this code differs in behaviour from the ``optparse`` (and |
| 235 |
``getopt``) version. |
| 236 |
|
| 237 |
.. seealso:: |
| 238 |
|
| 239 |
Module :mod:`optparse` |
| 240 |
Declarative command line option parsing. |
| 241 |
|
| 242 |
Module :mod:`argparse` |
| 243 |
More opinionated command line option and argument parsing library. |