summaryrefslogtreecommitdiff
path: root/argparse_utils.py
diff options
context:
space:
mode:
Diffstat (limited to 'argparse_utils.py')
-rw-r--r--argparse_utils.py29
1 files changed, 23 insertions, 6 deletions
diff --git a/argparse_utils.py b/argparse_utils.py
index 5a270f6..045d882 100644
--- a/argparse_utils.py
+++ b/argparse_utils.py
@@ -1,5 +1,7 @@
#!/usr/bin/python3
+"""Helpers for commandline argument parsing."""
+
import argparse
import datetime
import logging
@@ -15,13 +17,28 @@ logger = logging.getLogger(__name__)
class ActionNoYes(argparse.Action):
+ """An argparse Action that allows for commandline arguments like this:
+
+ cfg.add_argument(
+ '--enable_the_thing',
+ action=ActionNoYes,
+ default=False,
+ help='Should we enable the thing?'
+ )
+
+ This creates cmdline arguments:
+
+ --enable_the_thing
+ --no_enable_the_thing
+
+ """
def __init__(self, option_strings, dest, default=None, required=False, help=None):
if default is None:
msg = 'You must provide a default with Yes/No action'
logger.critical(msg)
raise ValueError(msg)
if len(option_strings) != 1:
- msg = 'Only single argument is allowed with YesNo action'
+ msg = 'Only single argument is allowed with NoYes action'
logger.critical(msg)
raise ValueError(msg)
opt = option_strings[0]
@@ -81,8 +98,8 @@ def valid_bool(v: Any) -> bool:
try:
return to_bool(v)
- except Exception:
- raise argparse.ArgumentTypeError(v)
+ except Exception as e:
+ raise argparse.ArgumentTypeError(v) from e
def valid_ip(ip: str) -> str:
@@ -247,10 +264,10 @@ def valid_duration(txt: str) -> datetime.timedelta:
try:
secs = parse_duration(txt)
- except Exception as e:
- raise argparse.ArgumentTypeError(e)
- finally:
return datetime.timedelta(seconds=secs)
+ except Exception as e:
+ logger.exception(e)
+ raise argparse.ArgumentTypeError(e) from e
if __name__ == '__main__':