Search code examples
pythonoptparse

Is it possible to make an option in optparse a mandatory?


Is it possible to make an option in optparse a mandatory?


Solution

  • I posted a comment earlier, but given that many other answers say No, not possible, here is how to do it:

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

    This makes the -f as mandatory.

    Using argparse is an alternative indeed, but that doesn't mean you can't do this in optparse also.