Python: How to make an option to be required in optparse?

前端 未结 9 2048
走了就别回头了
走了就别回头了 2021-02-05 00:57

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

9条回答
  •  佛祖请我去吃肉
    2021-02-05 01:27

    On the help message of each required variable Im writting a '[REQUIRED]' string at the beggining, to tag it to be parsed later, then I can simply use this function to wrap it around:

    def checkRequiredArguments(opts, parser):
        missing_options = []
        for option in parser.option_list:
            if re.match(r'^\[REQUIRED\]', option.help) and eval('opts.' + option.dest) == None:
                missing_options.extend(option._long_opts)
        if len(missing_options) > 0:
            parser.error('Missing REQUIRED parameters: ' + str(missing_options))
    
    parser = OptionParser()
    parser.add_option("-s", "--start-date", help="[REQUIRED] Start date")
    parser.add_option("-e", "--end-date", dest="endDate", help="[REQUIRED] End date")
    (opts, args) = parser.parse_args(['-s', 'some-date'])
    checkRequiredArguments(opts, parser)
    

提交回复
热议问题