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

Sander Sweers sander.sweers at gmail.com
Sat May 9 02:41:49 CEST 2009


2009/5/9 Terry Carroll <carroll at tjc.com>:
> 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.

Is the below what you are looking for?

>>> import optparse
>>> parser = optparse.OptionParser()
>>> parser.add_option('-f', '--format', type='choice', action='store', choices=('x','y','z'), dest='format')
>>> args = ['-f', 'd'] #Wrong format d
>>> options, restargs = parser.parse_args(args)
Usage:  [options]

: error: option -f: invalid choice: 'd' (choose from 'x', 'y', 'z')

Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
    parser.parse_args(args)
  File "C:\Python26\lib\optparse.py", line 1382, in parse_args
    self.error(str(err))
  File "C:\Python26\lib\optparse.py", line 1564, in error
    self.exit(2, "%s: error: %s\n" % (self.get_prog_name(), msg))
  File "C:\Python26\lib\optparse.py", line 1554, in exit
    sys.exit(status)
SystemExit: 2

>>> args = ['-f', 'x'] #Correct format x
>>> options, restargs = parser.parse_args(args)
>>> options.format
'x'

Greets
Sander


More information about the Tutor mailing list