Optparse - why can the last char parameter be ignored? With `--file` it behaves the same as` --fil`

Here is a simple code example:

from optparse import OptionParser parser = OptionParser() parser.add_option("-f", "--file", dest="filename") (options, args) = parser.parse_args() print options 

I saved it to a file and ran it. He works:

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

But here's the trick:

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

It also works with the undeclared fil option. Why does he behave this way?

+7
python optparse
source share
2 answers

You can see how optparse works by opening the optparse.py file in your python installation.

In the windows it was:

C:\Python27\Lib\optparse.py

The _match_abbrev function is on line 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) 

which is called _match_long_opt , which is called _process_long_opt

This seems to be documented in this section of the documentation:

opt_str

is a string of options that is visible on the command line that calls the callback. (If the shortened long version was used, opt_str will be a complete, canonical option string, for example. If the user places --foo on the command line as an abbreviation for -foobar, then opt_str will be "--foobar".)

If we change the example you provided:

 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 

In the test --fil example --fil you get an error message:

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

Thus, it can be used for shorter names, but if there is any ambiguity, then the opponent will cease.

+2
source share

optparse will try to match a partial or shorter option with any longer option names available. This is not particularly well documented, but it has always been done like this. Trying to find abbrev at https://docs.python.org/2/library/optparse.html#how-callbacks-are-called

Many other variant analysis libraries also do the same.

Note that optparse now deprecated.

+2
source share

All Articles