Python OPTPASE-为什么可以忽略选项的最后一个字符?对于'--file',其行为与'--fil'相同`

Python OPTPASE-为什么可以忽略选项的最后一个字符?对于'--file',其行为与'--fil'相同`,python,optparse,Python,Optparse,下面是一个简单的代码示例: from optparse import OptionParser parser = OptionParser() parser.add_option("-f", "--file", dest="filename") (options, args) = parser.parse_args() print options 我已将其保存到文件并运行。它的工作原理是: $ python script.py --file some_name {'filename': '

下面是一个简单的代码示例:

from optparse import OptionParser

parser = OptionParser()
parser.add_option("-f", "--file", dest="filename")

(options, args) = parser.parse_args()
print options
我已将其保存到文件并运行。它的工作原理是:

$ python script.py --file some_name
{'filename': 'some_name'}
但诀窍在于:

$ python script.py --fil some_name
{'filename': 'some_name'}
它还适用于未声明的选项
fil

为什么它会以这种方式运行?

optpasse
将尝试将部分或较短的选项与任何可用的较长选项名称进行匹配。它没有很好的文档记录,但它总是这样做的。正在尝试在中搜索
abbrev

许多其他选项解析库也这样做

请注意,
optparse
现在已被弃用。

您可以通过在python安装中打开
optparse.py
文件来查看其工作原理

在windows上,这是:

C:\Python27\Lib\optparse.py

\u match\u abbrev
功能位于第1675行:

def _match_abbrev(s, wordmap):
    """_match_abbrev(s : string, wordmap : {string : Option}) -> string

    Return the string key in 'wordmap' for which 's' is an unambiguous
    abbreviation.  If 's' is found to be ambiguous or doesn't match any of
    'words', raise BadOptionError.
    """
    # Is there an exact match?
    if s in wordmap:
        return s
    else:
        # Isolate all words with s as a prefix.
        possibilities = [word for word in wordmap.keys()
                         if word.startswith(s)]
        # No exact match, so there had better be just one possibility.
        if len(possibilities) == 1:
            return possibilities[0]
        elif not possibilities:
            raise BadOptionError(s)
        else:
            # More than one possible completion: ambiguous prefix.
            possibilities.sort()
            raise AmbiguousOptionError(s, possibilities)
\u match\u long\u opt
调用,由
\u process\u long\u opt

这似乎记录在文档的以下部分:

奥普图街

是命令行上触发回调的选项字符串。(如果使用了缩写长选项,则将使用opt_str。) 完整的规范选项字符串,例如,如果用户在 命令行作为--foobar的缩写,则opt_str将 “--foobar”。)

如果我们将您提供的示例更改为:

from optparse import OptionParser

parser = OptionParser()
parser.disable_interspersed_args()
parser.add_option("-f", "--file", dest="filename")
parser.add_option("-z", "--film", dest="filmname")

(options, args) = parser.parse_args()
print options
对于
--fil
的测试用例,您会得到一个错误:

error: ambiguous option: --fil (--file, --film?)

因此,可以使用较短的名称,但如果出现任何歧义,optpass将停止。

比这更好的是,
--fi
&
--f
也适用于我。我猜只要没有歧义,你就可以少用一些字符如果你不需要缩写,新版本的argparse(但不是不推荐的optparse)。谢谢你的详细回复。我下次应该更仔细地阅读文档)