diff options
Diffstat (limited to 'Doc/library/getopt.rst')
-rw-r--r-- | Doc/library/getopt.rst | 36 |
1 files changed, 29 insertions, 7 deletions
diff --git a/Doc/library/getopt.rst b/Doc/library/getopt.rst index 6a95142..bcfc4b5 100644 --- a/Doc/library/getopt.rst +++ b/Doc/library/getopt.rst @@ -1,13 +1,23 @@ -:mod:`getopt` --- Parser for command line options -================================================= +:mod:`getopt` --- C-style parser for command line options +========================================================= .. module:: getopt :synopsis: Portable parser for command line options; support both short and long option names. +**Source code:** :source:`Lib/getopt.py` + +-------------- + +.. note:: + The :mod:`getopt` module is a parser for command line options whose API is + designed to be familiar to users of the C :c:func:`getopt` function. Users who + are unfamiliar with the C :c:func:`getopt` function or who would like to write + less code and get better help and error messages should consider using the + :mod:`argparse` module instead. This module helps scripts to parse the command line arguments in ``sys.argv``. -It supports the same conventions as the Unix :cfunc:`getopt` function (including +It supports the same conventions as the Unix :c:func:`getopt` function (including the special meanings of arguments of the form '``-``' and '``--``'). Long options similar to those supported by GNU software may be used as well via an optional third argument. @@ -25,11 +35,11 @@ exception: be parsed, without the leading reference to the running program. Typically, this means ``sys.argv[1:]``. *shortopts* is the string of option letters that the script wants to recognize, with options that require an argument followed by a - colon (``':'``; i.e., the same format that Unix :cfunc:`getopt` uses). + colon (``':'``; i.e., the same format that Unix :c:func:`getopt` uses). .. note:: - Unlike GNU :cfunc:`getopt`, after a non-option argument, all further + Unlike GNU :c:func:`getopt`, after a non-option argument, all further arguments are considered also non-options. This is similar to the way non-GNU Unix systems work. @@ -136,9 +146,21 @@ In a script, typical usage is something like this:: if __name__ == "__main__": main() +Note that an equivalent command line interface could be produced with less code +and more informative help and error messages by using the :mod:`argparse` module:: + + import argparse + + if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-o', '--output') + parser.add_argument('-v', dest='verbose', action='store_true') + args = parser.parse_args() + # ... do something with args.output ... + # ... do something with args.verbose .. .. seealso:: - Module :mod:`optparse` - More object-oriented command line option parsing. + Module :mod:`argparse` + Alternative command line option and argument parsing library. |