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

查看:19
本文介绍了禁用 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天全站免登陆