Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 880
Alex Avatar asked Jan 04 '11 11:01

Alex


People also ask

Is Optparse deprecated?

Deprecated since version 3.2: The optparse module is deprecated and will not be developed further; development will continue with the argparse module.

How do you add options in Python?

add_option("-f", attr=value, ....) And to define an option with only a long option string: parser. add_option("--foo", attr=value, ....)

What is Optparse in Ruby?

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.


2 Answers

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

like image 21
gruszczy Avatar answered Nov 15 '22 15:11

gruszczy


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.

like image 81
user225312 Avatar answered Nov 15 '22 15:11

user225312