禁用argparse和optparse的唯一前缀匹配
当我使用Python的argparse或optparse命令行参数解析器时,参数的任何唯一前缀都被视为有效,例如
$ ./buildall.py --help
usage: buildall.py [-h] [-f]
Build all repositories
optional arguments:
-h, --help show this help message and exit
-f, --force Build dirty repositories
与--help
,一起使用--hel
,--he
用于帮助选项以及--forc
和--fo
强制选项。
可以以某种方式关闭此行为吗?我想获取不完整参数的错误消息。
-
仅在Python
3.5中添加了禁用缩写的长选项的功能。从argparse
文档中:如果缩写不明确(前缀与唯一选项匹配),则 默认情况下 该
parse_args()
方法允许将长选项缩写为前缀。 可以通过将
allow_abbrev 设置 为 来禁用此功能 。 __ __False
因此,如果您使用的是Python 3.5,则可以使用以下代码创建解析器
allow_abbrev=False
:parser = argparse.ArgumentParser(..., allow_abbrev=False)
如果您使用的是optparse或3.5之前版本的argparse,则只需要使用缩写选项即可。