开发者

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

开发者 https://www.devze.com 2023-02-02 02:41 出处:网络
Is it possible to make an option in optparse a mand开发者_JS百科atory?I posted a comment earlier, but given that many other answers say No, not possible, here is how to do it:

Is it possible to make an option in optparse a mand开发者_JS百科atory?


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消