How to generate error when argument are not supplied and there is no explicit defults (in optparse)?
rurpy at yahoo.com
rurpy at yahoo.com
Sat Oct 15 17:22:41 EDT 2011
On 10/14/2011 03:29 PM, Peng Yu wrote:
> Hi,
>
> The following code doesn't give me error, even I don't specify the
> value of filename from the command line arguments. filename gets
> 'None'. I checked the manual, but I don't see a way to let
> OptionParser fail if an argument's value (which has no default
> explicitly specified) is not specified. I may miss some thing in the
> manual. Could any expert let me know if there is a way to do so?
> Thanks!
>
> #!/usr/bin/env python
>
> from optparse import OptionParser
>
> usage = 'usage: %prog [options] arg1 arg2'
> parser = OptionParser(usage=usage)
> parser.set_defaults(verbose=True)
> parser.add_option('-f', '--filename')
>
> #(options, args) = parser.parse_args(['-f', 'file.txt'])
> (options, args) = parser.parse_args()
>
> print options.filename
You can check it yourself.
I find I use a pretty standard pattern with optparse:
def main (args, opts):
...
def parse_cmdline ():
p = OptionParser()
p.add_option('-f', '--filename')
options, args = parser.parse_args()
if not options.filename:
p.error ("-f option required")
if len (args) != 2:
p.error ("Expected exactly 2 arguments")
# Other checks can obviously be done here too.
return args, options
if __name__ == '__main__':
args, opts = parse_cmdline()
main (args, opts)
While one can probably subclass OptionParser or use callbacks
to achieve the same end, I find the above approach simple and
easy to follow.
I also presume you know that you have can optparse produce a
usage message by adding 'help' arguments to the add_option()
calls?
And as was mentioned in another post, argparse in Python 2.7
(or in earlier Pythons by downloading/installing it yourself)
can do the checking you want.
More information about the Python-list
mailing list