Sohaib Sohaib - 1 year ago 115
Python Question

Specify format for input arguments argparse python

I have a python script that requires some command line inputs and I am using argparse for parsing them. I found the documentation a bit confusing and couldn't find a way to check for a format in the input parameters. What I mean by checking format is explained with this example script:

parser.add_argument('-s', "--startdate", help="The Start Date - format YYYY-MM-DD ", required=True)
parser.add_argument('-e', "--enddate", help="The End Date format YYYY-MM-DD (Inclusive)", required=True)
parser.add_argument('-a', "--accountid", type=int, help='Account ID for the account for which data is required (Default: 570)')
parser.add_argument('-o', "--outputpath", help='Directory where output needs to be stored (Default: ' + os.path.dirname(os.path.abspath(__file__)))

I need to check for option
that the input by the user is in the format
. Is there an option in argparse that I do not know of which accomplishes this.

Answer Source

Per the documentation:

The type keyword argument of add_argument() allows any necessary type-checking and type conversions to be performed ... type= can take any callable that takes a single string argument and returns the converted value

You could do something like:

def valid_date(s):
        return datetime.strptime(s, "%Y-%m-%d")
    except ValueError:
        msg = "Not a valid date: '{0}'.".format(s)
        raise argparse.ArgumentTypeError(msg)

Then use that as type:

parser.add_argument('-s', "--startdate", 
                    help="The Start Date - format YYYY-MM-DD ", 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download