option argument length
Peter Otten
__peter__ at web.de
Sun Dec 4 17:04:26 EST 2005
Ritesh Raj Sarraf wrote:
> My program uses mostly "option arguments" hence my len(args) value is
> always zero. I need to check if the user has passed the correct number of
> "option arguments". Something like:
>
> (options,args) = parser.parse_args()
>
> len(options) != 1 or len(options) > 2:
> print "Incorrect number of arguments passed."
>
> How do I accomplish it ?
Judging from your code sample invention is the mother of that necessity.
You can pass a custom Values object with a __len__() method
class MyValues:
def __len__(self):
return len(self.__dict__)
# ...
options, args = parser.parse_args(values=MyValues())
but you should do your users a favour and give them meaningful error
messages. I can't conceive how you could achieve this by checking the
number of options. Explicit constraint checks like
options, args = parser.parse_args()
if options.eat_your_cake and options.have_it:
parser.error("Sorry, you cannot eat your cake and have it")
will increase your script's usability and make it easier to maintain for
only a tiny amount of work.
Peter
More information about the Python-list
mailing list