I've read this http://docs.python.org/release/2.6.2/library/optparse.html
But I'm not so clear how to make an option to be required in optparse?
I've tried to set "required=1" but I got an error:
invalid keyword arguments: required
I want to make my script require --file
option to be input by users. I know that the action
keyword gives you error when you don't supply value to --file
whose action="store_true"
.
Deprecated since version 3.2: The optparse module is deprecated and will not be developed further; development will continue with the argparse module. optparse is a more convenient, flexible, and powerful library for parsing command-line options than the old getopt module.
flags defines a distributed command line system, replacing systems like getopt() , optparse , and manual argument processing. Rather than an application having to define all flags in or near main() , each Python module defines flags that are useful to it.
You can implement a required option easily.
parser = OptionParser(usage='usage: %prog [options] arguments') parser.add_option('-f', '--file', dest='filename', help='foo help') (options, args) = parser.parse_args() if not options.filename: # if filename is not given parser.error('Filename not given')
Since if not x
doesn't work for some(negative,zero) parameters,
and to prevent lots of if tests, i preferr something like this:
required="host username password".split() parser = OptionParser() parser.add_option("-H", '--host', dest='host') parser.add_option("-U", '--user', dest='username') parser.add_option("-P", '--pass', dest='password') parser.add_option("-s", '--ssl', dest='ssl',help="optional usage of ssl") (options, args) = parser.parse_args() for r in required: if options.__dict__[r] is None: parser.error("parameter %s required"%r)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With