Search code examples
pythonoptparse

Python 2.7 optparse not reading 2nd flag


Can someone help me out here? I'm not sure what I'm doing wrong but I can't seem to get my second option to be read from the command line.

from optparse import OptionParser

parser=OptionParser()
parser.add_option("-s", action="store", type="string", dest="scenario")
parser.add_option("-l", action="store", type="string", dest="logger")
(options, args)=parser.parse_args()

print options.scenario
print options.logger
print options

Print Results

>>python test.py -sfoo -lbar
foo
None
{'logger': None, 'scenario': 'foo'}

Additionally, I cannot put a space in between the flag and argument -sfoo is ok but -s foo is not. It's pretty annoying. Can anyone see what I am doing wrong? Thanks in advance.


Solution

  • As @user3757614 suggests in his comment, use argparse instead.

    import argparse
    
    parser = argparse.ArgumentParser()
    
    parser.add_argument('-s', '--scenario', required=True, dest="scenario")
    parser.add_argument('-l', '--logger', required=True, dest="logger")
    
    args = parser.parse_args()
    
    print args
    print args.scenario
    print args.logger
    

    And in the command line:

    $ python test.py -s test1 -l test2
    Namespace(logger='test2', scenario='test1')
    test1
    test2