Is it possible to make an option in optparse a mandatory?
Is it possible to make an option in optparse a mandatory?
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.
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 option is by defeinition optional :-) If you need to make something mandatory, use argparse
and set a positional argument.
You can install argparse separately. code.google.com/p/argparse Then, when you upgrade python, you can migrate painlessly. –
Aleman
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.
© 2022 - 2024 — McMap. All rights reserved.
optparse
docs, it is stated there clearly. – Alemanargparse
allows for required options? To quote,argparse
docs:Optparse refuses to support these features, preferring purity over practicality.
– Yeryerevanoptparse
module is deprecated, making an option mandatory seems like an oxymoron... – Ferocious