Specify format for input arguments argparse python

前端 未结 3 2064
难免孤独
难免孤独 2020-12-02 11:49

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

3条回答
  •  不知归路
    2020-12-02 12:22

    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):
        try:
            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", 
                        required=True, 
                        type=valid_date)
    

提交回复
热议问题