禁用argparse和optparse的唯一前缀匹配 [英] Disable unique prefix matches for argparse and optparse

查看:85
本文介绍了禁用argparse和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 to False.

因此,如果您使用的是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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆