Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to make an option to be required in optparse?

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".

like image 359
jack Avatar asked Dec 10 '10 09:12

jack


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. optparse is a more convenient, flexible, and powerful library for parsing command-line options than the old getopt module.

What are option flags in Python?

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.


2 Answers

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') 
like image 173
user225312 Avatar answered Oct 11 '22 21:10

user225312


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) 
like image 39
Serge M. Avatar answered Oct 11 '22 21:10

Serge M.