【问题标题】:How to include regex choices in python ArgumentParser.add_argument()?如何在 python ArgumentParser.add_argument() 中包含正则表达式选择?
【发布时间】:2020-04-23 20:53:54
【问题描述】:

对于 Python 的 ArgumentParser.add_argument() 方法,我将如何在 choices kwarg 中包含正则表达式?

例如,假设我希望创建自己的自定义挂载程序:

# file: my_mount.py
from argparse import ArgumentParser

# some simple choices to help illustrate 
option_choices = {'ro|rw', 'user=.*', 'do=[a-z]{1,10}', 'allow_other'}

if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument('-s', '--share', dest='share')
    parser.add_argument('-m', '--mount-point', dest='mnt_pt')
    parser.add_argument('-o', dest='options', action='append', 
                        choices=option_choices, 
                        help='Options for mounting - see choices '
                             'expressions set for valid options')

    args, _ = parser.parse_known_args()
    # do some fancy stuff to do with mounting filesystems...

我的想法是,我可以根据一组简单的正则表达式过滤掉有效的选项,尤其是在所有可能性中手动编码都是一件苦差事,例如{'do=nothing', 'do=something', 'do=anything'...},但在调用 python my_mount.py -h 时也可以方便地保留选择列表。我最初的想法是有一个自定义的action,但这似乎与在add_argument() 中指定choices 时不兼容

【问题讨论】:

  • 你不能。您需要接受任何字符串,然后执行assert any(re.match(expr, opt) is not None for expr in option_choices for opt in args.options) 或类似操作。只需将'accepts: {}'.format(option_choices) 添加到--options 的帮助参数中即可。您不需要依赖 ArgParses 自动检查。

标签: python regex command-line-arguments


【解决方案1】:

我正在研究一个类似的问题,并决定使用type 进行验证。

这允许您使用可调用对象来执行验证。因此,不要使用选项,而是使用 type 来指定一个可调用的对象,以替代您的正则表达式匹配。

如果您想在某个容器中保留选择,那么您也可以这样做。或者,如果您必须仅使用选项,您可以定义一个验证输入的自定义容器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-14
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2016-09-29
    • 2015-03-05
    • 2017-10-25
    相关资源
    最近更新 更多