leas
leas

Reputation: 301

Option Parser does not match argument

I have a simple python (v2.7) script (test.py)

#!/usr/bin/python

import sys
from optparse import OptionParser

def main():
    parser = OptionParser()
    parser.add_option("--files", dest="files", 
                      metavar="FILES", default=None, 
                      help="A file pattern matching ottcall logs.")
    (options, args) = parser.parse_args()


    print "FILES_PATTERN %s" % options.files

    if not options.files:
        parser.error("Files_pattern option is mandatory - Abort execution.")

    return 0

if __name__ == "__main__":
    sys.exit(main())

User must provide a file pattern or a filename

Run script in command line if option is missing returns error:

python test.py
FILES_PATTERN None
Usage: test.py [options]

test.py: error: Files_pattern option is mandatory - Abort execution.

If option files is missing some letters (--fil instead of --files):

python test.py --fil "a_pattern_for_files"
FILES_PATTERN a_pattern_for_files

I think I should have an error like the following

python test.py --fl "a_pattern_for_files"
Usage: test.py [options]

test.py: error: no such option: --fl

Why don't I get an error from OptionParser when I use --fil instead of the correct argument --files ?

Not only I do not get an error but variable files stores the value: a_pattern_for_files (which is printed).

I am expecting argument files to have value: None (default) unless in command line --files exists

Upvotes: 1

Views: 649

Answers (1)

user2357112
user2357112

Reputation: 281131

optparse allows abbreviated forms of long options. --fil is a prefix of --files and not a prefix of any other long options the program supports, so --fil is treated as equivalent to --files.

This is barely mentioned in the docs, and there is no option to turn it off. argparse has an option to turn it off, but only in Python 3.5+.

Upvotes: 1

Related Questions