»Core Development>Code coverage>Lib/getopt.py

Python code coverage for Lib/getopt.py

#countcontent
1n/a"""Parser for command line options.
2n/a
3n/aThis module helps scripts to parse the command line arguments in
4n/asys.argv. It supports the same conventions as the Unix getopt()
5n/afunction (including the special meanings of arguments of the form `-'
6n/aand `--'). Long options similar to those supported by GNU software
7n/amay be used as well via an optional third argument. This module
8n/aprovides two functions and an exception:
9n/a
10n/agetopt() -- Parse command line options
11n/agnu_getopt() -- Like getopt(), but allow option and non-option arguments
12n/ato be intermixed.
13n/aGetoptError -- exception (class) raised with 'opt' attribute, which is the
14n/aoption involved with the exception.
15n/a"""
16n/a
17n/a# Long option support added by Lars Wirzenius <liw@iki.fi>.
18n/a#
19n/a# Gerrit Holl <gerrit@nl.linux.org> moved the string-based exceptions
20n/a# to class-based exceptions.
21n/a#
22n/a# Peter Åstrand <astrand@lysator.liu.se> added gnu_getopt().
23n/a#
24n/a# TODO for gnu_getopt():
25n/a#
26n/a# - GNU getopt_long_only mechanism
27n/a# - allow the caller to specify ordering
28n/a# - RETURN_IN_ORDER option
29n/a# - GNU extension with '-' as first character of option string
30n/a# - optional arguments, specified by double colons
31n/a# - an option string with a W followed by semicolon should
32n/a# treat "-W foo" as "--foo"
33n/a
34n/a__all__ = ["GetoptError","error","getopt","gnu_getopt"]
35n/a
36n/aimport os
37n/atry:
38n/a from gettext import gettext as _
39n/aexcept ImportError:
40n/a # Bootstrapping Python: gettext's dependencies not built yet
41n/a def _(s): return s
42n/a
43n/aclass GetoptError(Exception):
44n/a opt = ''
45n/a msg = ''
46n/a def __init__(self, msg, opt=''):
47n/a self.msg = msg
48n/a self.opt = opt
49n/a Exception.__init__(self, msg, opt)
50n/a
51n/a def __str__(self):
52n/a return self.msg
53n/a
54n/aerror = GetoptError # backward compatibility
55n/a
56n/adef getopt(args, shortopts, longopts = []):
57n/a """getopt(args, options[, long_options]) -> opts, args
58n/a
59n/a Parses command line options and parameter list. args is the
60n/a argument list to be parsed, without the leading reference to the
61n/a running program. Typically, this means "sys.argv[1:]". shortopts
62n/a is the string of option letters that the script wants to
63n/a recognize, with options that require an argument followed by a
64n/a colon (i.e., the same format that Unix getopt() uses). If
65n/a specified, longopts is a list of strings with the names of the
66n/a long options which should be supported. The leading '--'
67n/a characters should not be included in the option name. Options
68n/a which require an argument should be followed by an equal sign
69n/a ('=').
70n/a
71n/a The return value consists of two elements: the first is a list of
72n/a (option, value) pairs; the second is the list of program arguments
73n/a left after the option list was stripped (this is a trailing slice
74n/a of the first argument). Each option-and-value pair returned has
75n/a the option as its first element, prefixed with a hyphen (e.g.,
76n/a '-x'), and the option argument as its second element, or an empty
77n/a string if the option has no argument. The options occur in the
78n/a list in the same order in which they were found, thus allowing
79n/a multiple occurrences. Long and short options may be mixed.
80n/a
81n/a """
82n/a
83n/a opts = []
84n/a if type(longopts) == type(""):
85n/a longopts = [longopts]
86n/a else:
87n/a longopts = list(longopts)
88n/a while args and args[0].startswith('-') and args[0] != '-':
89n/a if args[0] == '--':
90n/a args = args[1:]
91n/a break
92n/a if args[0].startswith('--'):
93n/a opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
94n/a else:
95n/a opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
96n/a
97n/a return opts, args
98n/a
99n/adef gnu_getopt(args, shortopts, longopts = []):
100n/a """getopt(args, options[, long_options]) -> opts, args
101n/a
102n/a This function works like getopt(), except that GNU style scanning
103n/a mode is used by default. This means that option and non-option
104n/a arguments may be intermixed. The getopt() function stops
105n/a processing options as soon as a non-option argument is
106n/a encountered.
107n/a
108n/a If the first character of the option string is `+', or if the
109n/a environment variable POSIXLY_CORRECT is set, then option
110n/a processing stops as soon as a non-option argument is encountered.
111n/a
112n/a """
113n/a
114n/a opts = []
115n/a prog_args = []
116n/a if isinstance(longopts, str):
117n/a longopts = [longopts]
118n/a else:
119n/a longopts = list(longopts)
120n/a
121n/a # Allow options after non-option arguments?
122n/a if shortopts.startswith('+'):
123n/a shortopts = shortopts[1:]
124n/a all_options_first = True
125n/a elif os.environ.get("POSIXLY_CORRECT"):
126n/a all_options_first = True
127n/a else:
128n/a all_options_first = False
129n/a
130n/a while args:
131n/a if args[0] == '--':
132n/a prog_args += args[1:]
133n/a break
134n/a
135n/a if args[0][:2] == '--':
136n/a opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
137n/a elif args[0][:1] == '-' and args[0] != '-':
138n/a opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
139n/a else:
140n/a if all_options_first:
141n/a prog_args += args
142n/a break
143n/a else:
144n/a prog_args.append(args[0])
145n/a args = args[1:]
146n/a
147n/a return opts, prog_args
148n/a
149n/adef do_longs(opts, opt, longopts, args):
150n/a try:
151n/a i = opt.index('=')
152n/a except ValueError:
153n/a optarg = None
154n/a else:
155n/a opt, optarg = opt[:i], opt[i+1:]
156n/a
157n/a has_arg, opt = long_has_args(opt, longopts)
158n/a if has_arg:
159n/a if optarg is None:
160n/a if not args:
161n/a raise GetoptError(_('option --%s requires argument') % opt, opt)
162n/a optarg, args = args[0], args[1:]
163n/a elif optarg is not None:
164n/a raise GetoptError(_('option --%s must not have an argument') % opt, opt)
165n/a opts.append(('--' + opt, optarg or ''))
166n/a return opts, args
167n/a
168n/a# Return:
169n/a# has_arg?
170n/a# full option name
171n/adef long_has_args(opt, longopts):
172n/a possibilities = [o for o in longopts if o.startswith(opt)]
173n/a if not possibilities:
174n/a raise GetoptError(_('option --%s not recognized') % opt, opt)
175n/a # Is there an exact match?
176n/a if opt in possibilities:
177n/a return False, opt
178n/a elif opt + '=' in possibilities:
179n/a return True, opt
180n/a # No exact match, so better be unique.
181n/a if len(possibilities) > 1:
182n/a # XXX since possibilities contains all valid continuations, might be
183n/a # nice to work them into the error msg
184n/a raise GetoptError(_('option --%s not a unique prefix') % opt, opt)
185n/a assert len(possibilities) == 1
186n/a unique_match = possibilities[0]
187n/a has_arg = unique_match.endswith('=')
188n/a if has_arg:
189n/a unique_match = unique_match[:-1]
190n/a return has_arg, unique_match
191n/a
192n/adef do_shorts(opts, optstring, shortopts, args):
193n/a while optstring != '':
194n/a opt, optstring = optstring[0], optstring[1:]
195n/a if short_has_arg(opt, shortopts):
196n/a if optstring == '':
197n/a if not args:
198n/a raise GetoptError(_('option -%s requires argument') % opt,
199n/a opt)
200n/a optstring, args = args[0], args[1:]
201n/a optarg, optstring = optstring, ''
202n/a else:
203n/a optarg = ''
204n/a opts.append(('-' + opt, optarg))
205n/a return opts, args
206n/a
207n/adef short_has_arg(opt, shortopts):
208n/a for i in range(len(shortopts)):
209n/a if opt == shortopts[i] != ':':
210n/a return shortopts.startswith(':', i+1)
211n/a raise GetoptError(_('option -%s not recognized') % opt, opt)
212n/a
213n/aif __name__ == '__main__':
214n/a import sys
215n/a print(getopt(sys.argv[1:], "a:b", ["alpha=", "beta"]))