From 9a31a8cbd58f67899d1a340da61b598a11550e6f Mon Sep 17 00:00:00 2001 From: Gabriel Filion Date: Mon, 26 Jul 2010 23:52:33 -0400 Subject: [PATCH] lib/options: Add an onabort argument to Options() 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 --- lib/bup/options.py | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/lib/bup/options.py b/lib/bup/options.py index c1a1455..dc4be49 100644 --- a/lib/bup/options.py +++ b/lib/bup/options.py @@ -14,17 +14,23 @@ class OptDict: return self[k] +def _default_onabort(msg): + sys.exit(97) + + class Options: - 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._onabort = onabort 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') @@ -74,15 +80,18 @@ class Options: else: out.append('\n') return ''.join(out).rstrip() + '\n' - - def usage(self): + + def usage(self, msg=""): sys.stderr.write(self._usagestr) - sys.exit(97) + e = self._onabort and self._onabort(msg) or None + if e: + raise e def fatal(self, s): - 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) -- 2.39.2