Help with optionparse recipe

Michele Simionato michele.simionato at gmail.com
Tue Jul 27 08:14:24 EDT 2004


Stephen Boulet <stephen.no at spam.theboulets.net.please> wrote in message news:<J8-dnXIMZ_V9d5jcRVn-pQ at speakeasy.net>...
> I'm having trouble with the "optionparse" recipe in the cookbook:
> 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278844
> 
> This does not give me the results I expected (namely the arguments on the
> command line for each flag):
> 
> #!/usr/bin/env python
> """An example script invoking optionparse, my wrapper around optparse.
> 
>   usage: %prog [options] args
>   -f, --file: file to attach
>   -s, --subject: email subject
>   -a, --address: email address
> """
> 
> import optionparse
> opt, args = optionparse.parse(__doc__)
> if not opt and not args:
>     optionparse.exit()
> if opt.file:
>     print opt.file
> if opt.subject:
>     print opt.subject
> if opt.address:
>     print opt.address
> 
> Result:
> 
> $ python opttest.py -f "myfile.txt" -s "Here's the file" \
>  -a someone at there.net
> True
> True
> True
> 
> What am I doing wrong here?

It is the docstring. Try with this:

"""An example script invoking optionparse, my wrapper around optparse.

  usage: %prog [options] args
  -f, --file=FILE: file to attach
  -s, --subject=SUBJECT: email subject
  -a, --address=ADDRESS: email address
"""

Technically "optionparse" works by parsing the docstring and it
distinguishes option arguments from flags by looking at the "=" sign.

               Michele Simionato



More information about the Python-list mailing list