+++ /dev/null
-"""Parser for command line options.\r
-\r
-This module helps scripts to parse the command line arguments in\r
-sys.argv. It supports the same conventions as the Unix getopt()\r
-function (including the special meanings of arguments of the form `-'\r
-and `--'). Long options similar to those supported by GNU software\r
-may be used as well via an optional third argument. This module\r
-provides two functions and an exception:\r
-\r
-getopt() -- Parse command line options\r
-gnu_getopt() -- Like getopt(), but allow option and non-option arguments\r
-to be intermixed.\r
-GetoptError -- exception (class) raised with 'opt' attribute, which is the\r
-option involved with the exception.\r
-"""\r
-\r
-# Long option support added by Lars Wirzenius <liw@iki.fi>.\r
-#\r
-# Gerrit Holl <gerrit@nl.linux.org> moved the string-based exceptions\r
-# to class-based exceptions.\r
-#\r
-# Peter Astrand <astrand@lysator.liu.se> added gnu_getopt().\r
-#\r
-# TODO for gnu_getopt():\r
-#\r
-# - GNU getopt_long_only mechanism\r
-# - allow the caller to specify ordering\r
-# - RETURN_IN_ORDER option\r
-# - GNU extension with '-' as first character of option string\r
-# - optional arguments, specified by double colons\r
-# - a option string with a W followed by semicolon should\r
-# treat "-W foo" as "--foo"\r
-\r
-__all__ = ["GetoptError","error","getopt","gnu_getopt"]\r
-\r
-import os\r
-\r
-class GetoptError(Exception):\r
- opt = ''\r
- msg = ''\r
- def __init__(self, msg, opt=''):\r
- self.msg = msg\r
- self.opt = opt\r
- Exception.__init__(self, msg, opt)\r
-\r
- def __str__(self):\r
- return self.msg\r
-\r
-error = GetoptError # backward compatibility\r
-\r
-def getopt(args, shortopts, longopts = []):\r
- """getopt(args, options[, long_options]) -> opts, args\r
-\r
- Parses command line options and parameter list. args is the\r
- argument list to be parsed, without the leading reference to the\r
- running program. Typically, this means "sys.argv[1:]". shortopts\r
- is the string of option letters that the script wants to\r
- recognize, with options that require an argument followed by a\r
- colon (i.e., the same format that Unix getopt() uses). If\r
- specified, longopts is a list of strings with the names of the\r
- long options which should be supported. The leading '--'\r
- characters should not be included in the option name. Options\r
- which require an argument should be followed by an equal sign\r
- ('=').\r
-\r
- The return value consists of two elements: the first is a list of\r
- (option, value) pairs; the second is the list of program arguments\r
- left after the option list was stripped (this is a trailing slice\r
- of the first argument). Each option-and-value pair returned has\r
- the option as its first element, prefixed with a hyphen (e.g.,\r
- '-x'), and the option argument as its second element, or an empty\r
- string if the option has no argument. The options occur in the\r
- list in the same order in which they were found, thus allowing\r
- multiple occurrences. Long and short options may be mixed.\r
-\r
- """\r
-\r
- opts = []\r
- if type(longopts) == type(""):\r
- longopts = [longopts]\r
- else:\r
- longopts = list(longopts)\r
- while args and args[0].startswith('-') and args[0] != '-':\r
- if args[0] == '--':\r
- args = args[1:]\r
- break\r
- if args[0].startswith('--'):\r
- opts, args = do_longs(opts, args[0][2:], longopts, args[1:])\r
- else:\r
- opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])\r
-\r
- return opts, args\r
-\r
-def gnu_getopt(args, shortopts, longopts = []):\r
- """getopt(args, options[, long_options]) -> opts, args\r
-\r
- This function works like getopt(), except that GNU style scanning\r
- mode is used by default. This means that option and non-option\r
- arguments may be intermixed. The getopt() function stops\r
- processing options as soon as a non-option argument is\r
- encountered.\r
-\r
- If the first character of the option string is `+', or if the\r
- environment variable POSIXLY_CORRECT is set, then option\r
- processing stops as soon as a non-option argument is encountered.\r
-\r
- """\r
-\r
- opts = []\r
- prog_args = []\r
- if isinstance(longopts, str):\r
- longopts = [longopts]\r
- else:\r
- longopts = list(longopts)\r
-\r
- # Allow options after non-option arguments?\r
- if shortopts.startswith('+'):\r
- shortopts = shortopts[1:]\r
- all_options_first = True\r
- elif os.environ.get("POSIXLY_CORRECT"):\r
- all_options_first = True\r
- else:\r
- all_options_first = False\r
-\r
- while args:\r
- if args[0] == '--':\r
- prog_args += args[1:]\r
- break\r
-\r
- if args[0][:2] == '--':\r
- opts, args = do_longs(opts, args[0][2:], longopts, args[1:])\r
- elif args[0][:1] == '-' and args[0] != '-':\r
- opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])\r
- else:\r
- if all_options_first:\r
- prog_args += args\r
- break\r
- else:\r
- prog_args.append(args[0])\r
- args = args[1:]\r
-\r
- return opts, prog_args\r
-\r
-def do_longs(opts, opt, longopts, args):\r
- try:\r
- i = opt.index('=')\r
- except ValueError:\r
- optarg = None\r
- else:\r
- opt, optarg = opt[:i], opt[i+1:]\r
-\r
- has_arg, opt = long_has_args(opt, longopts)\r
- if has_arg:\r
- if optarg is None:\r
- if not args:\r
- raise GetoptError('option --%s requires argument' % opt, opt)\r
- optarg, args = args[0], args[1:]\r
- elif optarg is not None:\r
- raise GetoptError('option --%s must not have an argument' % opt, opt)\r
- opts.append(('--' + opt, optarg or ''))\r
- return opts, args\r
-\r
-# Return:\r
-# has_arg?\r
-# full option name\r
-def long_has_args(opt, longopts):\r
- possibilities = [o for o in longopts if o.startswith(opt)]\r
- if not possibilities:\r
- raise GetoptError('option --%s not recognized' % opt, opt)\r
- # Is there an exact match?\r
- if opt in possibilities:\r
- return False, opt\r
- elif opt + '=' in possibilities:\r
- return True, opt\r
- # No exact match, so better be unique.\r
- if len(possibilities) > 1:\r
- # XXX since possibilities contains all valid continuations, might be\r
- # nice to work them into the error msg\r
- raise GetoptError('option --%s not a unique prefix' % opt, opt)\r
- assert len(possibilities) == 1\r
- unique_match = possibilities[0]\r
- has_arg = unique_match.endswith('=')\r
- if has_arg:\r
- unique_match = unique_match[:-1]\r
- return has_arg, unique_match\r
-\r
-def do_shorts(opts, optstring, shortopts, args):\r
- while optstring != '':\r
- opt, optstring = optstring[0], optstring[1:]\r
- if short_has_arg(opt, shortopts):\r
- if optstring == '':\r
- if not args:\r
- raise GetoptError('option -%s requires argument' % opt,\r
- opt)\r
- optstring, args = args[0], args[1:]\r
- optarg, optstring = optstring, ''\r
- else:\r
- optarg = ''\r
- opts.append(('-' + opt, optarg))\r
- return opts, args\r
-\r
-def short_has_arg(opt, shortopts):\r
- for i in range(len(shortopts)):\r
- if opt == shortopts[i] != ':':\r
- return shortopts.startswith(':', i+1)\r
- raise GetoptError('option -%s not recognized' % opt, opt)\r
-\r
-if __name__ == '__main__':\r
- import sys\r
- print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"])\r