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

jack picture jack · Dec 10, 2010 · Viewed 58k times · Source

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 set "required=1" but I got an error:

invalid keyword arguments: required

I want to make my script require --file option to be input by users. I know that the action keyword gives you error when you don't supply value to --file whose action="store_true".

Answer

user225312 picture user225312 · Dec 10, 2010

You can implement a required option easily.

parser = OptionParser(usage='usage: %prog [options] arguments')
parser.add_option('-f', '--file', 
                        dest='filename',
                        help='foo help')
(options, args) = parser.parse_args()
if not options.filename:   # if filename is not given
    parser.error('Filename not given')