如何定义ArgParse默认参数选择和“ Wildcard”,“需要验证的动态选择要接受?
目前,我正在使用argparse
模块在Python 3中构建命令行接口。
我有一个情况需要定义选择(例如“今日”,“昨天”,“ Week”
,...) - s subparser的 - 但也允许日期字符串,但前提是可以通过预定义的格式成功将其成功解析为dateTime.dateTime
(例如“%y-%m-%) d“),否则,一个例外将是提高
d。
parser.add_argument(
"-s",
"--start-date",
type=str,
default="today",
choices=["today", "yesterday", "week", <date>], # date should be accepted only if datetime.strptime(date, "%Y-%m-%d") is successful
help="start date help",
)
这有可能吗?
I'm currently building a command line interface in Python 3 with the argparse
module.
I have a situation where I need to define choices (e.g. "today", "yesterday", "week"
, ...) for an optional argparse
argument -s
of a subparser, but also allow a date string, but only if it can be successfully parsed as datetime.datetime
with a predefined format (e.g. "%Y-%m-%d"), otherwise an exception would be raise
d.
parser.add_argument(
"-s",
"--start-date",
type=str,
default="today",
choices=["today", "yesterday", "week", <date>], # date should be accepted only if datetime.strptime(date, "%Y-%m-%d") is successful
help="start date help",
)
Is this somehow possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从我之前的问题来看,我相信这足以满足您的需要,验证您的输入的自定义函数。如果是今天、昨天、星期的基本情况,则返回字符串,否则尝试解析日期对象。
您可以按照您认为合适的方式更改它,但这说明了您的需求。
From my previous question, I believe this will suffice you, the custom function that validates your input. If it is the base case with today, yesterday, week, you return the strung, otherwise you try to parse the date object.
You can change it however you see fit, but this illustrates your need.