473,289 Members | 2,106 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,289 software developers and data experts.

optparse help output

Dan
I've been using optparse for a while, and I have an option with a
number of sub-actions I want to describe in the help section:

parser.add_option("-a", "--action",
help=\
"""Current supported actions: create, build, import, exp_cmd and
interact.

create -- Vaguely depreciated, should create a new project, but it
is
not currently suppored. First create a project in SVN,
then
use import.

build -- Build the project (invoking make usually).

import -- Put the project under metaman control. Assumes that
the current working directory is a SVN-controlled
sandbox. Metaman checks out its own copy, does analysis
to determine dependencies and the metadata to be
collected.

interact -- Creates a MetaMan object and starts the python interactive
interpreter. Designed for debugging or advanced usage.
The MetaMan object is bound to the identifier 'mm'. Only
use this option if you know what you're doing.

exp_cmd -- add an experiment for strataman.
""")

Unfortunately, when I run the script with --help, this is what I get
for the -a option:
-aACTION, --action=ACTION
Current supported actions: create, build,
import,
exp_cmd and interact. create -- Vaguely
depreciated,
should create a new project, but it
is not
currently suppored. First create a project in
SVN, then
use import. build -- Build the project
(invoking
make usually). import -- Put the project
under
metaman control. Assumes that the
current
working directory is a SVN-controlled
sandbox. Metaman checks out its own copy, does
analysis
to determine dependencies and the metadata to
be
collected. interact -- Creates a MetaMan
object and
starts the python interactive
interpreter.
Designed for debugging or advanced usage.
The MetaMan object is bound to the identifier
'mm'.
Only use this option if you know
what
you're doing. exp_cmd -- add an experiment
for
strataman.

Is there any way to get the formatting I want?

-Dan

Oct 24 '07 #1
3 2073
I've been using optparse for a while, and I have an option with a
number of sub-actions I want to describe in the help section:

parser.add_option("-a", "--action",
help=\
[snipped formatted help]
""")

Unfortunately, when I run the script with --help, this is what I get
for the -a option:
[snipped munged formatting of help]
Is there any way to get the formatting I want?
I had the same issue:

http://groups.google.com/group/comp....f28e26af0699b1

and was directed by Ben Finney to check out a custom formatter.
I got it working to my satisfaction and posted it in that thread:

http://groups.google.com/group/comp....f28e26af0699b1

It may be a little more kind in what it does with your help-text.
If you need variant behavior you can take my code and mung it
even further.

The changes are basically a copy&paste (including the comments,
which Steven D'Aprano suggested might be better made into
docstrings) of the format_description() and format_option() calls
from the standard-library's source, and changing a few small
lines to alter the behavior of calls to textwrap.*

Hope this helps,

-tkc


Oct 24 '07 #2
Dan
On Oct 24, 12:06 pm, Tim Chase <python.l...@tim.thechases.comwrote:
I've been using optparse for a while, and I have an option with a
number of sub-actions I want to describe in the help section:
parser.add_option("-a", "--action",
help=\

[snipped formatted help]""")
Unfortunately, when I run the script with --help, this is what I get
for the -a option:

[snipped munged formatting of help]
Is there any way to get the formatting I want?

I had the same issue:

http://groups.google.com/group/comp....thread/thread/...

and was directed by Ben Finney to check out a custom formatter.
I got it working to my satisfaction and posted it in that thread:

http://groups.google.com/group/comp....f28e26af0699b1

It may be a little more kind in what it does with your help-text.
If you need variant behavior you can take my code and mung it
even further.

The changes are basically a copy&paste (including the comments,
which Steven D'Aprano suggested might be better made into
docstrings) of the format_description() and format_option() calls
from the standard-library's source, and changing a few small
lines to alter the behavior of calls to textwrap.*

Hope this helps,

-tkc
Thanks, Tim!

That was incredibly helpful. I did alter it to format paragraphs, but
maintain the double newlines. Also, I made a few changes to work with
the 2.3 version of optparse. Posted below for anyone who might want
it. (Also to work as a standalone .py file)

-Dan
# From Tim Chase via comp.lang.python.

from optparse import IndentedHelpFormatter
import textwrap

class IndentedHelpFormatterWithNL(IndentedHelpFormatter) :
def format_description(self, description):
if not description: return ""
desc_width = self.width - self.current_indent
indent = " "*self.current_indent
# the above is still the same
bits = description.split('\n')
formatted_bits = [
textwrap.fill(bit,
desc_width,
initial_indent=indent,
subsequent_indent=indent)
for bit in bits]
result = "\n".join(formatted_bits) + "\n"
return result

def format_option(self, option):
# The help for each option consists of two parts:
# * the opt strings and metavars
# eg. ("-x", or "-fFILENAME, --file=FILENAME")
# * the user-supplied help string
# eg. ("turn on expert mode", "read data from FILENAME")
#
# If possible, we write both of these on the same line:
# -x turn on expert mode
#
# But if the opt string list is too long, we put the help
# string on a second line, indented to the same column it would
# start in if it fit on the first line.
# -fFILENAME, --file=FILENAME
# read data from FILENAME
result = []
opts = option.option_strings
opt_width = self.help_position - self.current_indent - 2
if len(opts) opt_width:
opts = "%*s%s\n" % (self.current_indent, "", opts)
indent_first = self.help_position
else: # start help on same line as opts
opts = "%*s%-*s " % (self.current_indent, "", opt_width, opts)
indent_first = 0
result.append(opts)
if option.help:
help_text = option.help
# Everything is the same up through here
help_lines = []
help_text = "\n".join([x.strip() for x in
help_text.split("\n")])
for para in help_text.split("\n\n"):
help_lines.extend(textwrap.wrap(para, self.help_width))
if len(help_lines):
# for each paragraph, keep the double newlines..
help_lines[-1] += "\n"
# Everything is the same after here
result.append("%*s%s\n" % (
indent_first, "", help_lines[0]))
result.extend(["%*s%s\n" % (self.help_position, "", line)
for line in help_lines[1:]])
elif opts[-1] != "\n":
result.append("\n")
return "".join(result)

Oct 24 '07 #3
Dan wrote:
On Oct 24, 12:06 pm, Tim Chase <python.l...@tim.thechases.comwrote:
>>I've been using optparse for a while, and I have an option with a
number of sub-actions I want to describe in the help section:
parser.add_option("-a", "--action",
help=\
[snipped formatted help]""")
>>Unfortunately, when I run the script with --help, this is what I get
for the -a option:
[snipped munged formatting of help]
>>Is there any way to get the formatting I want?
I had the same issue:

http://groups.google.com/group/comp....thread/thread/...

and was directed by Ben Finney to check out a custom formatter.
I got it working to my satisfaction and posted it in that thread:

http://groups.google.com/group/comp....f28e26af0699b1
That was incredibly helpful. I did alter it to format paragraphs, but
maintain the double newlines. Also, I made a few changes to work with
the 2.3 version of optparse. Posted below for anyone who might want
it. (Also to work as a standalone .py file)
You might consider posting it to the optik tracker:

http://optik.sourceforge.net/

A lot of people have had similar requests.

Steve
Oct 24 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Henry Ludemann | last post by:
I've been writing an optparse alternative (using getopt) that is at a stage where I'd be interested in people's opinions. It allows you to easily creating command line interfaces to existing...
8
by: T | last post by:
I have a short program using optparse.OptionParser that prints out help message with -h flag: % myprog.py -h usage: myprog.py input_file options: -h, --help show this help...
4
by: rick | last post by:
Consider the following piece of code: parser = optparse.OptionParser(usage="usage: %prog <input filename> <output filename", add_help_option=False) parser.add_option("-d", type="string",...
2
by: braver | last post by:
Posted to the Optik list, but it seems defunct. Optik is now Python's optparse. I wonder how do you implement optional arguments to Optik. I.e., you can have an option -P -- the...
5
by: john.m.roach | last post by:
I'm trying to implement some simple command line options. Some of the 'help' sections are long and I would like to control line breaks. How do you do this? Thanks!
1
by: GustavoTabares | last post by:
Hello, I'm trying to figure out if the following is a bug or if I'm using the remove_option in the wrong way. #!/usr/bin/env python import optparse parser = optparse.OptionParser()...
7
by: wannymahoots | last post by:
optparse seems to be escaping control characters that I pass as arguments on the command line. Is this a bug? Am I missing something? Can this be prevented, or worked around? This behaviour...
10
by: James | last post by:
Hi, I would like to know your thoughts on a proposed change to optparse that I have planned. It is possible to add default values to multiple options using the set_defaults. However, when adding...
0
by: John O'Hagan | last post by:
Here's a strange one for you: I have a generator function which produces lists of numbers and takes options which influence the output. The generator contains a loop, and to enable the options...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.