Search code examples
pythonbashoptparse

Python optparse not accepting options


I have written a function that accepts up to 4 options and 2 arguments. The options are -1, -2, -3, and -u. By default, their values are set to true, true, true, and false, respectively, but enabling any of the options causes that value to flip. Problem is, even when I specify, say,

python comm.py -1 -2 -u test test2

and print the option's values, they still show the default values. Below is the relevant portion of my code:

...
...
...
parser.add_option("-1", action="store_false", dest="xcol1", default=True, help="...")
parser.add_option("-2", action="store_false", dest="xcol2", default=True, help="...")
parser.add_option("-3", action="store_false", dest="dups", default=True, help="...")
parser.add_option("-u", action="store_true", dest="donotsort", default=False, help="...")

options, args = parser.parse_args(sys.argv[2:])

xcol1=options.xcol1
xcol2=options.xcol2
dups=options.dups
donotsort=options.donotsort


print "xcol1:"
print xcol1
print "xcol 2:"
print xcol2
print "dups:"
print dups
print "donotsort:"
print donotsort
print args
...
...
...

Executing the aformentioned command with the above code will output:

True

False

True

True

test, test2

i.e., the default values. It really should be outputting "False, False, True, True, ...), since options 1, 2, and u are enabled. What am I doing wrong? Is it something to do with the parser, because I'm not 100% sure I'm using the parser correctly.

Additionally, when I list the options as -12u instead of -1 -2 -u, it behaves differently - the boolean values are different


Solution

  • Should be

    options, args = parser.parse_args()
    

    Also add in:

    print options
    

    Results in:

    xcol1:
    True
    xcol 2:
    True
    dups:
    True
    donotsort:
    False
    ['test', 'test2']
    {'dups': True, 'donotsort': False, 'xcol2': True, 'xcol1': True}
    

    Explanation:

    sys.argv is a list, something like [{myScript.py}, {args...}]. Therefore, sys.argv[2:] gets rid of your flags.

    Given:

    import sys
    print sys.argv
    

    Results:

    >>> python showArgs.py -12u
    >>> ['showArgs.py', '-12u']
    

    Also, according to the official docs, optparse is deprecated in favor of argparse.