Search code examples
pythonoptparse

python optparse treat next option as the option argument for the current one when it's missing


I use optparse to parse the command options for my script. I have -f and -c options that both require an option argument. But when it's missing, it will treat the next option as option argument for the current option. e.g.

./myScript -f -c

this will treat "-c" as option argument for "-f" instead of complaining about option argument missing for "-f" and "-c". For other normal scenarios, it works fine.

Thank your for any information and solutions!

update: solution,by using argparse, this problem can be avoided. it exits with an error complaining about missing argument for options.


Solution

  • optparse is deprecated from python 2.7 on, so you should use the argparse module, which has this behaviour built in:

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument('-f')
    parser.add_argument('-c')
    
    parser.parse_args(['-f', 'f_val', '-c', 'c_val'])   #works as expected
    parser.parse_args(['-f', '-c'])                     #errors as expected
    

    If you are left with python < 2.7 and the optparse module, you can easily do it with a custom check after the parsing stage:

    parser = OptionParser('usage')
    parser.add_option("-f", "--ff", dest="f_value")
    parser.add_option("-c", "--cc", dest="c_value")
    
    (options, args) = parser.parse_args()
    
    if options.f_value == '-c':
        print 'error: -f requires an argument'
        exit(1)