optparse - 为什么可以忽略该选项的最后一个字符?使用`--file`它的行为与`--fil`相同

时间:2016-04-05 14:51:19

标签: python optparse

以下是代码的简单示例:

$ python script.py --file some_name
{'filename': 'some_name'}

我已将其保存到文件并运行。它有效:

$ python script.py --fil some_name
{'filename': 'some_name'}

但这是诀窍:

fil

它也适用于未声明的选项999-999-9999。 为什么它以这种方式表现?

2 个答案:

答案 0 :(得分:2)

optparse将尝试将部分或更短的选项与任何可用的更长选项名称匹配。它没有特别好的记录,但它总是这样做。尝试在https://docs.python.org/2/library/optparse.html#how-callbacks-are-called

中搜索abbrev

许多其他选项解析库都是这样做的。

请注意,optparse现已弃用。

答案 1 :(得分:2)

您可以通过在python安装中打开optparse.py文件来了解optparse的工作原理。

在Windows上,这是:

C:\Python27\Lib\optparse.py

_match_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)

_match_long_opt

调用_process_long_opt调用的内容

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

  

opt_str

     

是在命令行上看到的触发回调的选项字符串。 (如果使用了缩写长选项,则opt_str将为   完整的,规范的选项字符串 - 例如。如果用户将--foo放在   命令行作为--foobar的缩写,然后opt_str将   " - foobar的&#34)

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

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?)

所以可以使用较短的名字,但如果有任何歧义,optparse将会停止。

相关问题