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)