あなたのpythonインストールでoptparse.py
ファイルを開くことによって、optparseの動作を確認できます。 Windows上で
は、このでした:
C:\Python27\Lib\optparse.py
_match_abbrev
機能がライン1675上にある:_process_long_opt
によって呼び出され_match_long_opt
によって呼び出され
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)
これはに表示されますドキュメントのthisセクションに文書化されています:
opt_str
is the option string seen on the command-line that’s triggering the callback. (If an abbreviated long option was used, opt_str will be the full, canonical option string—e.g. if the user puts --foo on the command-line as an abbreviation for --foobar, then opt_str will be "--foobar".)
我々はあなたが提供した例変更した場合:--fil
のテストケースで
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
を、あなたがエラーを取得:
error: ambiguous option: --fil (--file, --film?)
短い名前を使用するので、そのOKあいまいさがある場合には、optparseは停止します。
それよりもうまくいくと、 '--fi'と' --f'も私のために働きます。私は、あいまいさがない限り、より少ない文字で逃げることができると推測しています – SiHa
略語が欲しくない場合は、新しいバージョンのargparse(廃止されたoptparseではなく)[それを無効にする](https ://stackoverflow.com/questions/33900846/)。 –