[Tutor] Optparse question: if only certain values are acceptable

Alan Gauld alan.gauld at btinternet.com
Sat May 9 10:10:46 CEST 2009


"Terry Carroll" <carroll at tjc.com> wrote 

> The toy summary is that I want to have the following command format:
> 
>  prognam -f FORMAT
> 
> Where FORMAT, if specified, must be one of "X", "Y", or "Z".
> 
> In otherwords, if the user enters:
> 
> progname -f X
> 
> It runs, producing its output in format X.  Similar if "Y" or "Z" is
> specified instead of "X".
> 
> But if the user specifies
> 
> progname -f A
> 
> I want it to spit up because A is not a recognized format.
> 
> I don't see anything in the docs that directly addresses this.  Is this 
> something that I should use the callback parameter for?

Which part do you not understand or do you believe is not addresssed?
optparse can certainly allow you to specify the -f option and store the 
user entered value. 

Your code will have to act accordingly based on the value, optparse 
won't do that bit.

And for the invalid option value I think you can handle that too, 
in an else clause. 

Thats the easiest way to use it IMHO.

You can define a callback for your option but with only one 
option I dont see much point, you still need the value if/else 
inside the callback.

You can define the list of values too (via choice) but again 
catching anything other than X,Y,Z is just as easy using an 
else clause in your case.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list