首页 文章

指定输入参数argparse python的格式

提问于
浏览
67

我有一个需要一些命令行输入的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-e ,用户输入的格式为 YYYY-MM-DD . 在argparse中是否有一个选项,我不知道哪个完成了这个 .

3 回答

  • 5

    the documentation

    add_argument()的type关键字参数允许执行任何必要的类型检查和类型转换... type =可以接受任何带有单个字符串参数的callable并返回转换后的值

    你可以这样做:

    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)
    
  • 173

    只是为了添加上面的答案,如果你想将它保持为单行,你可以使用lambda函数 . 例如:

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

    旧线程,但问题至少仍然与我相关!

  • 52

    对于通过搜索引擎点击这一点的其他人:在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)
    

相关问题