1

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

dimitris lepipas
  • 263
  • 3
  • 15
  • You aren't asking a question here. What is it you're looking to achieve? – TMarks Jun 04 '18 at 15:31
  • 1
    If you're having issues with the `OptionParse` package, and are using Python 2.7+, try using `argparse`. – TMarks Jun 04 '18 at 15:32
  • Please provide a complete, runnable test file, including all your imports (and any shebang line that tells what interpreter you are using). Also make sure that your indentation is correct (edit your question and fix it). – NickD Jun 04 '18 at 15:35

1 Answers1

1

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+.

user2357112
  • 260,549
  • 28
  • 431
  • 505