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

3

10

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

Execratory answered 4/1, 2011 at 11:8 Comment(6)
Yes, it is possible. Check out the answer to this question here (stackoverflow.com/questions/4407539)Yeryerevan
Yes, but you shouldn't do that, because that's against convention and standard of command line interface. There is a reason, why options can't be made mandatory. Read the optparse docs, it is stated there clearly.Aleman
Ok, then why is that argparse allows for required options? To quote, argparse docs: Optparse refuses to support these features, preferring purity over practicality.Yeryerevan
I believe you have answered your own question :-) I am using argparse, because I like positional argument functionality, but I keep to command line standards.Aleman
I understand the point you are trying to make, but there is a difference between 'not possible' and 'should be avoided.'Yeryerevan
Besides the fact that the optparse module is deprecated, making an option mandatory seems like an oxymoron...Ferocious
Y
20

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.

Yeryerevan answered 4/1, 2011 at 11:18 Comment(2)
Okay, 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.Sarmentum
Indeed, optparse has no role, this is just a way to make an option required.Yeryerevan
A
8

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

Aleman answered 4/1, 2011 at 11:9 Comment(1)
You can install argparse separately. code.google.com/p/argparse Then, when you upgrade python, you can migrate painlessly.Aleman
S
2

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.

Sarmentum answered 4/1, 2011 at 11:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.