指定输入参数argparse python的格式 [英] Specify format for input arguments argparse python
问题描述
我有一个需要一些命令行输入的python脚本,并且我正在使用argparse对其进行解析.我发现文档有点混乱,找不到在输入参数中检查格式的方法.这个示例脚本解释了我检查格式的意思:
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__)))
我需要检查选项-s
和-e
用户输入的格式为YYYY-MM-DD
.在argparse中有一个我不知道哪个选项可以完成此任务.
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.
推荐答案
每文档:
add_argument()
的type
关键字参数允许执行任何必要的类型检查和类型转换...type=
可以接受带有单个字符串参数并返回转换后值的任何可调用项
The
type
keyword argument ofadd_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
您可以执行以下操作:
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)
然后将其用作type
:
parser.add_argument("-s",
"--startdate",
help="The Start Date - format YYYY-MM-DD",
required=True,
type=valid_date)
这篇关于指定输入参数argparse python的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!