python 限定输入类型_python 限定输入类型_指定输入参数argparse python的格式

43333

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 -s and -e that the input by the user is in the format YYYY-MM-DD. Is there an option in argparse that I do not know of which accomplishes this.

解决方案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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值