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

Dim*_*kov 7 python optparse

这是代码的简单示例:

from optparse import OptionParser

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

(options, args) = parser.parse_args()
print options
Run Code Online (Sandbox Code Playgroud)

我已将其保存到文件并运行.有用:

$ python script.py --file some_name
{'filename': 'some_name'}
Run Code Online (Sandbox Code Playgroud)

但这是诀窍:

$ python script.py --fil some_name
{'filename': 'some_name'}
Run Code Online (Sandbox Code Playgroud)

它也适用于未声明的选项fil.为什么它以这种方式表现?

Noe*_*lkd 2

您可以通过打开以下命令查看optparse 的工作原理optparse.pypython 安装中的文件

\n\n

在 Windows 上这是:

\n\n

C:\\Python27\\Lib\\optparse.py

\n\n

_match_abbrev函数位于第 1675 行:

\n\n
def _match_abbrev(s, wordmap):\n    """_match_abbrev(s : string, wordmap : {string : Option}) -> string\n\n    Return the string key in \'wordmap\' for which \'s\' is an unambiguous\n    abbreviation.  If \'s\' is found to be ambiguous or doesn\'t match any of\n    \'words\', raise BadOptionError.\n    """\n    # Is there an exact match?\n    if s in wordmap:\n        return s\n    else:\n        # Isolate all words with s as a prefix.\n        possibilities = [word for word in wordmap.keys()\n                         if word.startswith(s)]\n        # No exact match, so there had better be just one possibility.\n        if len(possibilities) == 1:\n            return possibilities[0]\n        elif not possibilities:\n            raise BadOptionError(s)\n        else:\n            # More than one possible completion: ambiguous prefix.\n            possibilities.sort()\n            raise AmbiguousOptionError(s, possibilities)\n
Run Code Online (Sandbox Code Playgroud)\n\n

哪个被调用_match_long_opt哪个被调用_process_long_opt

\n\n

这似乎记录在文档的

\n\n
\n

选项_str

\n\n

是在命令行上看到的\xe2\x80\x99s 触发回调的选项字符串。(如果使用了缩写的长选项,则 opt_str 将是完整的、规范的选项字符串\xe2\x80\x94,例如,如果用户将 --foo 放在\n 命令行上作为 --foobar 的缩写,那么 opt_str 将是\n "--foobar"。)

\n
\n\n

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

\n\n
from optparse import OptionParser\n\nparser = OptionParser()\nparser.disable_interspersed_args()\nparser.add_option("-f", "--file", dest="filename")\nparser.add_option("-z", "--film", dest="filmname")\n\n(options, args) = parser.parse_args()\nprint options\n
Run Code Online (Sandbox Code Playgroud)\n\n

与测试用例--fil,您会得到一个错误:

\n\n
error: ambiguous option: --fil (--file, --film?)\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n