Search code examples
pythonoptparse

Python OptParse combine multiple options


Example code:

import optparse
import sys
parser = optparse.OptionParser(usage='python %prog -t -b -q',
                           prog=sys.argv[0],
                           )
parser.add_option('-t','--tt', action="store_true", help="Blah",dest="t")

parser.add_option('-b','--bb', action="store_true", help="Blah",dest="b")

parser.add_option('-q','--qq', action="store_true", help="Blah",dest="q")

options, args = parser.parse_args()

Is there anyway to combine all these options:

python test.py -tbq

And get this result:

options.q  = True

options.t  = True

options.b  = True

Solution

  • The options can be combined as you want. The program run with -tb

    import optparse, sys 
    parser = optparse.OptionParser(usage='python %prog -t -b -q',
                               prog=sys.argv[0],
                                                          )   
    parser.add_option('-t','--tt', action="store_true", help="Blah",dest="t")
    parser.add_option('-b','--bb', action="store_true", help="Blah",dest="b")
    parser.add_option('-q','--qq', action="store_true", help="Blah",dest="q")
    options, args = parser.parse_args()
    
    print options
    

    produces

    {'q': None, 'b': True, 't': True}