1 # The software in this package is distributed under the GNU General
2 # Public License version 2 (with a special exception described below).
4 # A copy of GNU General Public License (GPL) is included in this distribution,
5 # in the file COPYING.GPL.
7 # As a special exception, if other files instantiate templates or use macros
8 # or inline functions from this file, or you compile this file and link it
9 # with other works to produce a work based on this file, this file
10 # does not by itself cause the resulting work to be covered
11 # by the GNU General Public License.
13 # However the source code for this file must still be made available
14 # in accordance with section (3) of the GNU General Public License.
16 # This exception does not invalidate any other reasons why a work based
17 # on this file might be covered by the GNU General Public License.
20 argparse_helpers: Some convenience helpers for argparse
23 - NonExitingParser: a subclass of ArgumentParser that does not do sys.exit(2)
24 on parse error but instead raises a ArgParserWantsExit exception.
25 - function existing_file which can be used as a type in add_argument() calls
27 .. codeauthor:: Intra2net
30 from argparse import ArgumentParser, ArgumentTypeError
31 from os.path import isfile
34 class ArgParserWantsExit(Exception):
36 Exception raised from NonExitingParser instead of calling sys.exit(2).
39 def __init__(self, message):
40 super(ArgParserWantsExit, self).__init__("Error parsing args: " +
44 class NonExitingParser(ArgumentParser):
45 """ArgumentParser that does not call sys.exit(2) on parse failure.
47 Calling sys.exit also just raises a SystemExit exception. But that is not
48 a subclass of Exception and not as explicit and specific as this one.
50 Convenient e.g. for global try-except blocks e.g. in a daemon::
56 parser = NonExitingParser()
58 args = parser.parse_args()
59 # ... rest of your program ...
60 except Exception as exc:
61 log.error('uncaught exception: exc') # will always show in log
64 def error(self, message):
65 """Called when error occurred parsing args. Raise error, not exit."""
66 raise ArgParserWantsExit(message)
69 def existing_file(filename):
71 Function that raises ArgumentTypeError if argument is not an existing file.
73 Returns filename if it is valid. Can be used as `type` argument in
74 :py:meth:`argparse.ArgumentParser.add_argument`
76 If you want to open the file, you can as well use the python built-in
77 :py:class:`argparse.FileType` instead.
81 raise ArgumentTypeError('{} is not an existing file'.format(filename))
84 def existing_file_or_empty(filename=''):
86 Like :py:func:`existing_file` but accepts empty filename (returns '' then).
88 if not filename.strip():
90 return existing_file(filename)