mikecharles
2/8/2016 - 2:50 PM

Validate command line date argument in Python

Validate command line date argument in Python

def date_arg(value):
    """
    Validate the --dates argument

    Function will ensure that the --dates argument matches a given regex.
    Possible values of the date are:

    - YYYYMMDD (eg. 20120515)
    - YYYYMMDD-YYYYMMDD (eg. 20140115-20140315)
    - yesterday
    - today

    Parameters
    ----------

    - value - *string* - automatically passed by the ArgumentParser object

    Returns
    -------

    Returns the value back to the ArgumentParser object

    Exceptions
    ----------

    - argparse.ArgumentTypeError - if the passed argument doesn't match the
    regex
    """
    # Regex check
    if not re.match('^(\d{8}|\d{8}-\d{8}|yesterday|today)$', value):
        raise argparse.ArgumentTypeError("must be in the form MMDD, "
                                         "MMDD-MMDD, yesterday, "
                                         "or today".format(value))
    # Make sure end date is >= start date
    if re.match("\d{8}-\d{8}", value):
        start, end = value.split('-')
        if not end >= start:
            raise argparse.ArgumentTypeError("The start date is less than the "
                                             "end date")
    return value

Validates a --dates argument in Python with the following possible formats:

  • YYYYMMDD (eg. 20120515)
  • YYYYMMDD-YYYYMMDD (eg. 20140115-20140315)
  • yesterday
  • today

To use this function, reference it in the argparse setup:

# ------------------------------------------------------------------------------
# Function to parse command-line arguments
#
def parse_args(argv):
    """
    Parse the command line args

    Note that the argv argument will be parsed instead of sys.argv because
    the test suite will need to execute the main() function, and will
    therefore need to pass the given arguments to that function, as opposed
    to the main() function getting them from sys.argv.

    Parameters
    ----------

    - argv - *list of strings* - argument list containing the elements from
    sys.argv, except the first element (sys.argv[0]) which is the script name
    """
    # Create an ArgumentParser object
    parser = argparse.ArgumentParser(add_help=False, usage='%(prog)s [OPTIONS]')

    # Add a required argument group
    group = parser.add_argument_group('required arguments')

    # Add arguments
    group.add_argument(
        '-d', '--dates', dest='dates',
        help='month and day of the valid date(s) to create stats for (YYYYMMDD or '
             'YYYYMMDD-YYYYMMDD)',
        metavar='<DATE(S)>', required=True, type=date_arg)
    # If no options are set, print help and exit, otherwise parse args
    if len(argv) <= 1:
        parser.print_help()
        sys.exit()
    else:
        args = parser.parse_args(argv)
    # If the help option was set, print help and exit
    if hasattr(args, 'help'):
        parser.print_help()
        sys.exit()

    return args