Is it possible to make an option in optparse a mandatory?
Deprecated since version 3.2: The optparse module is deprecated and will not be developed further; development will continue with the argparse module.
add_option("-f", attr=value, ....) And to define an option with only a long option string: parser. add_option("--foo", attr=value, ....)
OptionParser is a class for command-line option analysis. It is much more advanced, yet also easier to use, than GetoptLong, and is a more Ruby-oriented solution.
option is by defeinition optional :-) If you need to make something mandatory, use argparse
and set a positional argument.
http://docs.python.org/dev/library/argparse.html
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With