Optparse and help formatting?

Tim Chase python.list at tim.thechases.com
Sat Sep 29 21:43:50 EDT 2007


I've been learning the ropes of the optparse module and have been
having some trouble getting the help to format the way I want.

I want to specify parts of an option's help as multiline.
However, the optparse formatter seems to eat newlines despite my
inability to find anything in optparse.py that does something
obvious like .replace("\n", " ") to eat the newlines I stick in
the help.  It also seems to mung tabs.  An example from my code:

parser.add_option("-x", "--extended",
  action="callback",
  callback=callback_test,
  type="string",  # required to get metavar to show in help
  dest="test",
  metavar="CONF",
  help="a comma-separated list of options.\n"
    "s=[YYYY]MMDD,n=NAME,c=COLOR\n"
    "s,start=[YYYY]MMDD\n"
    "\tstart day of period (default, current day)\n"
  ...
  )

which would accept options that looked something like

  test.py -x s=20070401,n=XR71,c=black

(my callback_test breaks apart parser.rargs[0] to deal with the
funky params).

However, when I display the help, its reformatting eats the
newlines in my help-string and strangely looks like it converts
my tabs to spaces.

Any hints on how to either work around the problem or fix it?

As a side note, I couldn't find documented anywhere that if you
have a "metavar" setting for a "callback" parameter, you have to
specify the "type" to get the metavar to show up in the help as
"-x CONF, --extended=CONF".  If you don't specify the type, it
will display as "-x, --extended" without the metavar, even if you
specify one.  Hackishly setting type="string" made the metavar
appear.

Thanks for any hints,

-tkc
(python2.4 on Debian, FWIW)







More information about the Python-list mailing list