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