禁用 argparse 和 optparse 的唯一前缀匹配 [英] Disable unique prefix matches for argparse and optparse
问题描述
当我使用 Python 的 argparse 或 optparse 命令行参数解析器时,参数的任何唯一前缀都被认为是有效的,例如
When I use Python's argparse or optparse command line argument parser, any unique prefix of an argument is considered valid, e.g.
$ ./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
用于强制选项.
works with --help
, --hel
, --he
for the help option as well as --forc
and --fo
for the force option.
可以以某种方式关闭此行为吗?我想收到关于不完整参数的错误消息.
Can this behavior be turned off somehow? I want to get an error message for incomplete arguments.
推荐答案
仅在 Python 3.5 中添加了禁用缩写长选项的功能.来自 argparse
文档一个>:
The ability to disable abbreviated long options was only added in Python 3.5. From the argparse
documentation:
parse_args()
方法默认允许将长选项缩写为前缀,如果缩写是明确的(前缀匹配唯一选项)...可以通过将 allow_abbrev 设置为 False
来禁用此功能.
The
parse_args()
method by default allows long options to be abbreviated to a prefix, if the abbreviation is unambiguous (the prefix matches a unique option) ... This feature can be disabled by setting allow_abbrev toFalse
.
因此,如果您使用的是 Python 3.5,则可以使用 allow_abbrev=False
创建解析器:
So if you're on Python 3.5, you can create your parser with allow_abbrev=False
:
parser = argparse.ArgumentParser(..., allow_abbrev=False)
如果您使用的是 optparse 或 3.5 之前的 argparse,则您只需要接受缩写选项即可.
If you're on optparse or pre-3.5 argparse, you just have to live with abbreviated options.
这篇关于禁用 argparse 和 optparse 的唯一前缀匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!