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"
.
I'm forced to use python 2.6 for our solution so I'm stick to optparse module. Here is solution I found to check for required options that works without specifying second time list of required options. Thus when you add new option you don't have to add it's name into the list of options to check.
My criteria for required option - option value should be not None and this options doesn't have default (user didn't specified add_option(default="...",...).
I'm also stuck on python 2.6 (pining for python2.7 and argparse, which not only has required arguments, but lets me specify that one of a set must be supplied); my approach requires a second pass, but lets me prompt for missing arguments unless running in batch mode:
(I'm thinking of making my own parser class that has common options for global configs baked in.)
Another answer to this question cited parser.error, which I was unfamiliar with when I wrote the code, but might have been a better choice.
As the optparse module is deprecated since version 2.7, you will probably find some more up to date examples here: Dead simple argparse example wanted: 1 argument, 3 results
There are at least two methods of implementing required options with
optparse
. As mentioned in the docs page, optparse doesn’t prevent you from implementing required options, but doesn’t give you much help at it either. Find below the examples found in files distributed with the source.Although please note that
optparse
module is deprecated since version 2.7 and will not be developed further. You should useargparse
module instead.Version 1: Add a method to OptionParser which applications must call after parsing arguments:
Source:
docs/lib/required_1.txt
Version 2: Extend Option and add a required attribute; extend OptionParser to ensure that required options are present after parsing:
Source:
docs/lib/required_2.txt
The current answer with the most votes would not work if, for example, the argument were an integer or float for which zero is a valid input. In these cases it would say that there is an error. An alternative (to add to the several others here) would be to do e.g.
You can implement a required option easily.