【发布时间】: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