这是代码的简单示例:
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.为什么它以这种方式表现?
您可以通过打开以下命令查看optparse 的工作原理optparse.pypython 安装中的文件
在 Windows 上这是:
\n\nC:\\Python27\\Lib\\optparse.py
这_match_abbrev函数位于第 1675 行:
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)\nRun 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\nfrom 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\nRun Code Online (Sandbox Code Playgroud)\n\n与测试用例--fil,您会得到一个错误:
error: ambiguous option: --fil (--file, --film?)\nRun Code Online (Sandbox Code Playgroud)\n\n所以使用较短的名称是可以的,但如果有任何歧义,optparse 将停止。
\n| 归档时间: |
|
| 查看次数: |
169 次 |
| 最近记录: |