all Python 3argparsefunction
getopt.getopt()
getopt — C-style parsing
Parses command-line arguments in the Unix getopt style: short -a, -b value and long --name options; returns pairs and the rest.
Syntax
opts, args = getopt.getopt(args, shortopts, longopts=[])
Parsing stops at the first non-option argument: in ['file', '-c'] the -c ends up in the remainder rather than among the options — gnu_getopt handles intermixed arguments. Pass sys.argv[1:], without the program name. Values are always strings, and a flag without a value gets ''. A long name may be shortened to an unambiguous prefix: --verb matches --verbose. There is no help or type checking — use argparse in new code.
Examples
import getopt
opts, rest = getopt.getopt(['-a', '-b', 'val', 'file', '-c'], 'ab:c')
print(opts) # → [('-a', ''), ('-b', 'val')]
print(rest) # → ['file', '-c'] — -c после файла не разобран
print(getopt.getopt(['--verb', 'x'], '', ['verbose'])) # → ([('--verbose', '')], ['x'])
import getopt
try:
getopt.getopt(['-x'], 'a')
except getopt.GetoptError as e:
print(e, e.opt) # → option -x not recognized x
See also
Open in the full glossarydocs.python.orgReport an inaccuracy