我有一个需要一些命令行输入的 Python 脚本,我正在使用argparse
用于解析它们。我发现文档有点混乱,找不到检查输入参数格式的方法。我通过以下示例脚本解释了检查格式的含义:
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
and -e
用户输入的格式为YYYY-MM-DD
。有没有一个选项argparse
我不知道哪个能做到这一点?
Per 文档 https://docs.python.org/3/library/argparse.html#type:
The type
的关键字参数add_argument()
允许执行任何必要的类型检查和类型转换...的参数type
可以是任何接受单个字符串的可调用对象。
你可以这样做:
def valid_date(s):
try:
return datetime.strptime(s, "%Y-%m-%d")
except ValueError:
msg = "not a valid date: {0!r}".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
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)