指定输入参数的格式 argparse python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25470844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:15:51  来源:igfitidea点击:

Specify format for input arguments argparse python

pythonpython-2.7argparse

提问by Sohaib

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:

我有一个需要一些命令行输入的 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__)))

I need to check for option -sand -ethat 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.

我需要检查选项-s以及-e用户输入的格式是否为YYYY-MM-DD. argparse 中是否有我不知道的选项可以实现这一点。

采纳答案by jonrsharpe

Per the documentation:

根据文档

The typekeyword 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

所述type的关键字参数add_argument()允许执行任何必要的类型检查和类型转换...type=可以采取任何可调用采用单个字符串参数,并返回转换后的值

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:

然后将其用作type

parser.add_argument("-s", 
                    "--startdate", 
                    help="The Start Date - format YYYY-MM-DD", 
                    required=True, 
                    type=valid_date)

回答by Evan V

Just to add on to the answer above, you can use a lambda function if you want to keep it to a one-liner. For example:

只是为了补充上面的答案,如果您想将其保持为单行,您可以使用 lambda 函数。例如:

parser.add_argument('--date', type=lambda d: datetime.strptime(d, '%Y%m%d'))

Old thread but the question was still relevant for me at least!

旧线程,但这个问题至少对我来说仍然相关!

回答by Micha? Górny

For others who hit this via search engines: in Python 3.7, you can use the standard .fromisoformatclass method instead of reinventing the wheel for ISO-8601 compliant dates, e.g.:

对于通过搜索引擎点击此内容的其他人:在 Python 3.7 中,您可以使用标准.fromisoformat类方法而不是为符合 ISO-8601 的日期重新发明轮子,例如:

parser.add_argument('-s', "--startdate",
    help="The Start Date - format YYYY-MM-DD",
    required=True,
    type=datetime.date.fromisoformat)
parser.add_argument('-e', "--enddate",
    help="The End Date format YYYY-MM-DD (Inclusive)",
    required=True,
    type=datetime.date.fromisoformat)