Is it possible to make an option in optparse a mandatory?
Solution 1
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.
Solution 2
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
Solution 3
No, you can't. Either you can use argparse
and or you get the option value from using the optparse module and explicitly check if the optionvalue is defined (like in the optparse set it to some default like None and check for not None) and if it is not defined, call sys.exit()
asking the users to provide that option.
Alex
Updated on June 26, 2022Comments
-
Alex almost 2 years
Is it possible to make an option in optparse a mandatory?
-
Senthil Kumaran over 13 yearsOkay, this is what I meant by ( - optparse set it to some default like None and check for not None), I think should have provided an example. Thanks. BTW, this is not done by optparse, you are doing it by checking for the option's value in the program.
-
user225312 over 13 yearsIndeed,
optparse
has no role, this is just a way to make an option required. -
gruszczy over 13 yearsYou can install argparse separately. code.google.com/p/argparse Then, when you upgrade python, you can migrate painlessly.