Guido van Rossum | 4b8c6ea | 2000-02-04 15:39:30 +0000 | [diff] [blame] | 1 | """Parser for command line options. |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 2 | |
Guido van Rossum | 6d06094 | 1998-11-17 04:16:37 +0000 | [diff] [blame] | 3 | This module helps scripts to parse the command line arguments in |
| 4 | sys.argv. It supports the same conventions as the Unix getopt() |
| 5 | function (including the special meanings of arguments of the form `-' |
| 6 | and `--'). Long options similar to those supported by GNU software |
| 7 | may be used as well via an optional third argument. This module |
| 8 | provides a single function and an exception: |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 9 | |
Guido van Rossum | 6d06094 | 1998-11-17 04:16:37 +0000 | [diff] [blame] | 10 | getopt() -- Parse command line options |
Guido van Rossum | 80c33e5 | 1999-12-21 22:38:40 +0000 | [diff] [blame] | 11 | GetoptError -- exception (class) raised with 'opt' attribute, which is the |
| 12 | option involved with the exception. |
Guido van Rossum | 6d06094 | 1998-11-17 04:16:37 +0000 | [diff] [blame] | 13 | """ |
Guido van Rossum | 1550ff7 | 1996-09-11 19:43:52 +0000 | [diff] [blame] | 14 | |
Guido van Rossum | 6d06094 | 1998-11-17 04:16:37 +0000 | [diff] [blame] | 15 | # Long option support added by Lars Wirzenius <liw@iki.fi>. |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 16 | |
Fred Drake | a395ced | 2000-02-25 16:14:08 +0000 | [diff] [blame] | 17 | # Gerrit Holl <gerrit@nl.linux.org> moved the string-based exceptions |
| 18 | # to class-based exceptions. |
| 19 | |
Skip Montanaro | eccd02a | 2001-01-20 23:34:12 +0000 | [diff] [blame] | 20 | __all__ = ["GetoptError","error","getopt"] |
| 21 | |
Guido van Rossum | 80c33e5 | 1999-12-21 22:38:40 +0000 | [diff] [blame] | 22 | class GetoptError(Exception): |
| 23 | opt = '' |
| 24 | msg = '' |
Fred Drake | e1fd526 | 2001-01-08 15:39:32 +0000 | [diff] [blame] | 25 | def __init__(self, msg, opt): |
| 26 | self.msg = msg |
| 27 | self.opt = opt |
| 28 | Exception.__init__(self, msg, opt) |
Guido van Rossum | 80c33e5 | 1999-12-21 22:38:40 +0000 | [diff] [blame] | 29 | |
| 30 | def __str__(self): |
| 31 | return self.msg |
| 32 | |
| 33 | error = GetoptError # backward compatibility |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 34 | |
Guido van Rossum | 2c349bb | 1996-09-09 15:48:24 +0000 | [diff] [blame] | 35 | def getopt(args, shortopts, longopts = []): |
Guido van Rossum | 6d06094 | 1998-11-17 04:16:37 +0000 | [diff] [blame] | 36 | """getopt(args, options[, long_options]) -> opts, args |
| 37 | |
| 38 | Parses command line options and parameter list. args is the |
| 39 | argument list to be parsed, without the leading reference to the |
| 40 | running program. Typically, this means "sys.argv[1:]". shortopts |
| 41 | is the string of option letters that the script wants to |
| 42 | recognize, with options that require an argument followed by a |
| 43 | colon (i.e., the same format that Unix getopt() uses). If |
| 44 | specified, longopts is a list of strings with the names of the |
| 45 | long options which should be supported. The leading '--' |
| 46 | characters should not be included in the option name. Options |
| 47 | which require an argument should be followed by an equal sign |
| 48 | ('='). |
| 49 | |
| 50 | The return value consists of two elements: the first is a list of |
| 51 | (option, value) pairs; the second is the list of program arguments |
| 52 | left after the option list was stripped (this is a trailing slice |
| 53 | of the first argument). Each option-and-value pair returned has |
| 54 | the option as its first element, prefixed with a hyphen (e.g., |
| 55 | '-x'), and the option argument as its second element, or an empty |
| 56 | string if the option has no argument. The options occur in the |
| 57 | list in the same order in which they were found, thus allowing |
| 58 | multiple occurrences. Long and short options may be mixed. |
| 59 | |
| 60 | """ |
| 61 | |
| 62 | opts = [] |
| 63 | if type(longopts) == type(""): |
| 64 | longopts = [longopts] |
| 65 | else: |
| 66 | longopts = list(longopts) |
Tim Peters | dd699b6 | 2000-12-27 08:05:05 +0000 | [diff] [blame] | 67 | while args and args[0].startswith('-') and args[0] != '-': |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 68 | if args[0] == '--': |
| 69 | args = args[1:] |
| 70 | break |
Fred Drake | 1e7dfd3 | 2001-12-12 06:20:34 +0000 | [diff] [blame] | 71 | if args[0].startswith('--'): |
Guido van Rossum | 6d06094 | 1998-11-17 04:16:37 +0000 | [diff] [blame] | 72 | opts, args = do_longs(opts, args[0][2:], longopts, args[1:]) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 73 | else: |
Guido van Rossum | 6d06094 | 1998-11-17 04:16:37 +0000 | [diff] [blame] | 74 | opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:]) |
Guido van Rossum | c636014 | 1990-10-13 19:23:40 +0000 | [diff] [blame] | 75 | |
Guido van Rossum | 6d06094 | 1998-11-17 04:16:37 +0000 | [diff] [blame] | 76 | return opts, args |
Guido van Rossum | 2c349bb | 1996-09-09 15:48:24 +0000 | [diff] [blame] | 77 | |
Guido van Rossum | 6d06094 | 1998-11-17 04:16:37 +0000 | [diff] [blame] | 78 | def do_longs(opts, opt, longopts, args): |
Guido van Rossum | 1550ff7 | 1996-09-11 19:43:52 +0000 | [diff] [blame] | 79 | try: |
Fred Drake | a395ced | 2000-02-25 16:14:08 +0000 | [diff] [blame] | 80 | i = opt.index('=') |
Guido van Rossum | 1550ff7 | 1996-09-11 19:43:52 +0000 | [diff] [blame] | 81 | except ValueError: |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 82 | optarg = None |
Tim Peters | dd699b6 | 2000-12-27 08:05:05 +0000 | [diff] [blame] | 83 | else: |
| 84 | opt, optarg = opt[:i], opt[i+1:] |
Guido van Rossum | 2c349bb | 1996-09-09 15:48:24 +0000 | [diff] [blame] | 85 | |
Guido van Rossum | 1550ff7 | 1996-09-11 19:43:52 +0000 | [diff] [blame] | 86 | has_arg, opt = long_has_args(opt, longopts) |
| 87 | if has_arg: |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 88 | if optarg is None: |
| 89 | if not args: |
Guido van Rossum | 80c33e5 | 1999-12-21 22:38:40 +0000 | [diff] [blame] | 90 | raise GetoptError('option --%s requires argument' % opt, opt) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 91 | optarg, args = args[0], args[1:] |
Guido van Rossum | 1550ff7 | 1996-09-11 19:43:52 +0000 | [diff] [blame] | 92 | elif optarg: |
Guido van Rossum | 80c33e5 | 1999-12-21 22:38:40 +0000 | [diff] [blame] | 93 | raise GetoptError('option --%s must not have an argument' % opt, opt) |
Guido van Rossum | 6d06094 | 1998-11-17 04:16:37 +0000 | [diff] [blame] | 94 | opts.append(('--' + opt, optarg or '')) |
| 95 | return opts, args |
Guido van Rossum | 2c349bb | 1996-09-09 15:48:24 +0000 | [diff] [blame] | 96 | |
| 97 | # Return: |
| 98 | # has_arg? |
| 99 | # full option name |
| 100 | def long_has_args(opt, longopts): |
Tim Peters | d31b632 | 2000-12-29 02:17:56 +0000 | [diff] [blame] | 101 | possibilities = [o for o in longopts if o.startswith(opt)] |
| 102 | if not possibilities: |
Tim Peters | dd699b6 | 2000-12-27 08:05:05 +0000 | [diff] [blame] | 103 | raise GetoptError('option --%s not recognized' % opt, opt) |
Tim Peters | dd699b6 | 2000-12-27 08:05:05 +0000 | [diff] [blame] | 104 | # Is there an exact match? |
| 105 | if opt in possibilities: |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 106 | return False, opt |
Tim Peters | dd699b6 | 2000-12-27 08:05:05 +0000 | [diff] [blame] | 107 | elif opt + '=' in possibilities: |
Tim Peters | bc0e910 | 2002-04-04 22:55:58 +0000 | [diff] [blame] | 108 | return True, opt |
Tim Peters | dd699b6 | 2000-12-27 08:05:05 +0000 | [diff] [blame] | 109 | # No exact match, so better be unique. |
| 110 | if len(possibilities) > 1: |
| 111 | # XXX since possibilities contains all valid continuations, might be |
| 112 | # nice to work them into the error msg |
| 113 | raise GetoptError('option --%s not a unique prefix' % opt, opt) |
| 114 | assert len(possibilities) == 1 |
| 115 | unique_match = possibilities[0] |
| 116 | has_arg = unique_match.endswith('=') |
| 117 | if has_arg: |
| 118 | unique_match = unique_match[:-1] |
| 119 | return has_arg, unique_match |
Guido van Rossum | 2c349bb | 1996-09-09 15:48:24 +0000 | [diff] [blame] | 120 | |
Guido van Rossum | 6d06094 | 1998-11-17 04:16:37 +0000 | [diff] [blame] | 121 | def do_shorts(opts, optstring, shortopts, args): |
Guido van Rossum | 1550ff7 | 1996-09-11 19:43:52 +0000 | [diff] [blame] | 122 | while optstring != '': |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 123 | opt, optstring = optstring[0], optstring[1:] |
| 124 | if short_has_arg(opt, shortopts): |
| 125 | if optstring == '': |
| 126 | if not args: |
Fred Drake | 1e7dfd3 | 2001-12-12 06:20:34 +0000 | [diff] [blame] | 127 | raise GetoptError('option -%s requires argument' % opt, |
| 128 | opt) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 129 | optstring, args = args[0], args[1:] |
| 130 | optarg, optstring = optstring, '' |
| 131 | else: |
| 132 | optarg = '' |
Guido van Rossum | 6d06094 | 1998-11-17 04:16:37 +0000 | [diff] [blame] | 133 | opts.append(('-' + opt, optarg)) |
| 134 | return opts, args |
Guido van Rossum | 2c349bb | 1996-09-09 15:48:24 +0000 | [diff] [blame] | 135 | |
| 136 | def short_has_arg(opt, shortopts): |
Guido van Rossum | 1550ff7 | 1996-09-11 19:43:52 +0000 | [diff] [blame] | 137 | for i in range(len(shortopts)): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 138 | if opt == shortopts[i] != ':': |
Fred Drake | 1e7dfd3 | 2001-12-12 06:20:34 +0000 | [diff] [blame] | 139 | return shortopts.startswith(':', i+1) |
Guido van Rossum | 80c33e5 | 1999-12-21 22:38:40 +0000 | [diff] [blame] | 140 | raise GetoptError('option -%s not recognized' % opt, opt) |
Guido van Rossum | 2c349bb | 1996-09-09 15:48:24 +0000 | [diff] [blame] | 141 | |
| 142 | if __name__ == '__main__': |
Guido van Rossum | 1550ff7 | 1996-09-11 19:43:52 +0000 | [diff] [blame] | 143 | import sys |
| 144 | print getopt(sys.argv[1:], "a:b", ["alpha=", "beta"]) |