473,409 Members | 1,945 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,409 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 2077
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

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.