I\'ve read this http://docs.python.org/release/2.6.2/library/optparse.html
But I\'m not so clear how to make an option to be required in optparse?
I\'ve tried to
I'm forced to use python 2.6 for our solution so I'm stick to optparse module. Here is solution I found to check for required options that works without specifying second time list of required options. Thus when you add new option you don't have to add it's name into the list of options to check.
My criteria for required option - option value should be not None and this options doesn't have default (user didn't specified add_option(default="...",...).
def parse_cli():
"""parse and check command line options, shows help message
@return: dict - options key/value
"""
import __main__
parser = OptionParser(description=__main__.__doc__)
parser.add_option("-d", "--days", dest="days",
help="Number of days to process")
parser.add_option("-p", "--period", dest="period_length",default="2",
help="number or hours per iteration, default value=%default hours")
(options, args) = parser.parse_args()
"""get dictionary of options' default values.
in this example: { 'period_length': '2','days': None}"""
defaults = vars(parser.get_default_values())
optionsdict = vars(options)
all_none = False
for k,v in optionsdict.items():
if v is None and defaults.get(k) is None:
all_none = True
if all_none:
parser.print_help()
sys.exit()
return optionsdict