Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   optparse and counting arguments (not options) (http://www.velocityreviews.com/forums/t357532-optparse-and-counting-arguments-not-options.html)

Steven Bethard 05-10-2006 04:33 AM

optparse and counting arguments (not options)
 
I feel like I must be reinventing the wheel here, so I figured I'd post
to see what other people have been doing for this. In general, I love
the optparse interface, but it doesn't do any checks on the arguments.
I've coded something along the following lines a number of times:

class OptionArgParser(optparse.OptionParser):
def __init__(self, *args, **kwargs):
self.min_args = kwargs.pop('min_args', None)
self.max_args = kwargs.pop('max_args', None)
self.arg_values = kwargs.pop('arg_values', None)
optparse.OptionParser.__init__(self, *args, **kwargs)

def parse_args(self, args=None):
options, args = optparse.OptionParser.parse_args(self, args)
if self.min_args is not None and len(args) < self.min_args:
self.error('too few arguments')
if self.max_args is not None and len(args) > self.max_args:
self.error('too many arguments')
if self.arg_values is not None:
for arg, values in zip(args, self.arg_values):
if values is not None and arg not in values:
message = 'argument %r is not one of: %s'
self.error(message % (arg, ', '.join(values)))
return options, args

This basically lets me skip some simple checks by creating instances of
OptionArgParser instead of optparse.OptionParser, and supplying my new
options:

parser = OptionArgParser(
min_args=1, arg_values=[commands],
usage='%%prog [options] (%s) ...' % '|'.join(commands),
description='invoke one of the commands')

Is this problem already solved in some module that I've missed?

STeVe


All times are GMT. The time now is 12:20 PM.

Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57