Some times, we may want to parse a list of arguments and not have the
call to Options.parse() exit the program when it finds an unknown
argument.
Add an argument to the class' __init__ method that can be either a
function or a class (must be an exception class). If calling the
function or class constructor returns an object, this object will be
raised on abort.
Also add a convenience exception class named Fatal that can be
passed to Options() to exclusively catch situations in which
Options.parse() would have caused the program to exit.
Finally, set the default value to the onabort argument to call
sys.exit(97) as was previously the case.
Signed-off-by: Gabriel Filion <lelutin@gmail.com>
+def _default_onabort(msg):
+ sys.exit(97)
+
+
- def __init__(self, exe, optspec, optfunc=getopt.gnu_getopt):
+ def __init__(self, exe, optspec, optfunc=getopt.gnu_getopt,
+ onabort=_default_onabort):
self.exe = exe
self.optspec = optspec
self.exe = exe
self.optspec = optspec
+ self._onabort = onabort
self.optfunc = optfunc
self._aliases = {}
self._shortopts = 'h?'
self._longopts = ['help']
self._hasparms = {}
self._usagestr = self._gen_usage()
self.optfunc = optfunc
self._aliases = {}
self._shortopts = 'h?'
self._longopts = ['help']
self._hasparms = {}
self._usagestr = self._gen_usage()
def _gen_usage(self):
out = []
lines = self.optspec.strip().split('\n')
def _gen_usage(self):
out = []
lines = self.optspec.strip().split('\n')
else:
out.append('\n')
return ''.join(out).rstrip() + '\n'
else:
out.append('\n')
return ''.join(out).rstrip() + '\n'
+
+ def usage(self, msg=""):
sys.stderr.write(self._usagestr)
sys.stderr.write(self._usagestr)
+ e = self._onabort and self._onabort(msg) or None
+ if e:
+ raise e
- sys.stderr.write('error: %s\n' % s)
- return self.usage()
-
+ msg = 'error: %s\n' % s
+ sys.stderr.write(msg)
+ return self.usage(msg)
+
def parse(self, args):
try:
(flags,extra) = self.optfunc(args, self._shortopts, self._longopts)
def parse(self, args):
try:
(flags,extra) = self.optfunc(args, self._shortopts, self._longopts)