X-Git-Url: https://wannabe.guru.org/gitweb/?a=blobdiff_plain;f=argparse_utils.py;h=e8c2f5699bea4bceb67d22127a923099d0d143e5;hb=5f75cf834725ac26b289cc5f157af0cb71cd5f0e;hp=0ee2be9f8017093caeff732962ad9b4d10a993e7;hpb=4c315e387f18010ba0b5661744ad3c792f21d2d1;p=python_utils.git diff --git a/argparse_utils.py b/argparse_utils.py index 0ee2be9..e8c2f56 100644 --- a/argparse_utils.py +++ b/argparse_utils.py @@ -6,6 +6,9 @@ import logging import os from typing import Any +from overrides import overrides + + # This module is commonly used by others in here and should avoid # taking any unnecessary dependencies back on them. @@ -47,6 +50,7 @@ class ActionNoYes(argparse.Action): help=help ) + @overrides def __call__(self, parser, namespace, values, option_strings=None): if ( option_strings.startswith('--no-') or @@ -232,6 +236,28 @@ def valid_datetime(txt: str) -> datetime.datetime: raise argparse.ArgumentTypeError(msg) +def valid_duration(txt: str) -> datetime.timedelta: + """If the string is a valid time duration, return a + datetime.timedelta representing the period of time. Otherwise + maybe raise an ArgumentTypeError or potentially just treat the + time window as zero in length. + + >>> valid_duration('3m') + datetime.timedelta(seconds=180) + + >>> valid_duration('your mom') + datetime.timedelta(0) + + """ + from datetime_utils import parse_duration + try: + secs = parse_duration(txt) + except Exception as e: + raise argparse.ArgumentTypeError(e) + finally: + return datetime.timedelta(seconds=secs) + + if __name__ == '__main__': import doctest doctest.ELLIPSIS_MARKER = '-ANYTHING-'