如何定义ArgParse默认参数选择和“ Wildcard”,“需要验证的动态选择要接受?

发布于 2025-01-17 10:05:17 字数 637 浏览 3 评论 0原文

目前,我正在使用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 raised.

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花开半夏魅人心 2025-01-24 10:05:17

从我之前的问题来看,我相信这足以满足您的需要,验证您的输入的自定义函数。如果是今天、昨天、星期的基本情况,则返回字符串,否则尝试解析日期对象。

您可以按照您认为合适的方式更改它,但这说明了您的需求。

import argparse

def parse_date(s):
    if s.lower() in ["today", "yesterday", "week"]:
        return s
    
    return datetime.datetime.strptime(s, "%Y-%m-%d")

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument(
            "-s",
            "--start-date",
            type=lambda s: parse_date(s),
            default="today",
            help="start date help",
        )

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.

import argparse

def parse_date(s):
    if s.lower() in ["today", "yesterday", "week"]:
        return s
    
    return datetime.datetime.strptime(s, "%Y-%m-%d")

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument(
            "-s",
            "--start-date",
            type=lambda s: parse_date(s),
            default="today",
            help="start date help",
        )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文