OptParse description: newline / linebreak / Zeilenumbruch ?

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
arghargh
User
Beiträge: 81
Registriert: Donnerstag 4. September 2008, 22:26

Hi,

die Frage ist:

Wie lässt sich der description string von OptParse mit Zeilenumbrüchen formatieren? Das ist leider nicht vorgesehen.

Die Frage wurde hier schon nicht beantwortet:
http://www.python-forum.de/topic-2894.html

Nun gibt es aber die Möglichkeit, einen formatter anzugeben:
http://docs.python.org/dev/library/optp ... ing-parser

Der hier "umgebaut" wurde:
http://groups.google.com/group/comp.lan ... 26af0699b1

Wie man das zum Laufen bringt, steht hier:
http://bytes.com/forum/thread734066.html

Ich versuche es so:

Code: Alles auswählen

from optparse \
	import	OptionParser, \
			OptionGroup		# parse command line options and arguments

import optparse_linebreak

Code: Alles auswählen

	parser = OptionParser(...,
							formatter = optparse_linebreak.IndentedHelpFormatterWithNL())
Aber ich bekomme leider Fehler:

Code: Alles auswählen

in format_option_help
    result.append(formatter.format_option(option))
  File "optparse_linebreak.py", line 38, in format_option
    opts = option.option_strings
AttributeError: Option instance has no attribute 'option_strings'
Vielleicht kann mir jemand sagen, was da nicht funktioniert?

MfG

optparse_linbreak.py:

Code: Alles auswählen

# 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) 
arghargh
User
Beiträge: 81
Registriert: Donnerstag 4. September 2008, 22:26

Hallo,

leider weiss ich nicht, wie das funktioniert. Ich hatte gehofft, es einfach so benutzen zu können, wie es in den Links beschrieben wird. So versuche ich es ja auch.

Code: Alles auswählen

description (default: None)
    A paragraph of text giving a brief overview of your program. 
optparse reformats this paragraph to fit the current terminal width 
and prints it when the user requests help (after usage, but before 
the list of options). 
formatter (default: a new IndentedHelpFormatter)
    An instance of optparse.HelpFormatter that will be used for 
printing help text. optparse provides two concrete classes for this 
purpose: IndentedHelpFormatter and TitledHelpFormatter. 
Intern wird wohl OptParse den String "description" an den "formatter" übergeben.

Falls jemand den Fehler verfolgen kann, und mir kurz erläutert, wie er das macht, würde ich dabei auch gleich was lernen :-)
Alleine steh ich etwas ratlos vor der Fehlermeldung.
Benutzeravatar
snafu
User
Beiträge: 6738
Registriert: Donnerstag 21. Februar 2008, 17:31
Wohnort: Gelsenkirchen

arghargh
User
Beiträge: 81
Registriert: Donnerstag 4. September 2008, 22:26

Nein, ich glaube das ist etwas anderes. (?)
arghargh
User
Beiträge: 81
Registriert: Donnerstag 4. September 2008, 22:26

Teilweise mein Fehler: unter den Links ist auch eine geänderte Lösung zu finden, die ich fälschlicherweise übernommen habe.

Der funktionierende Code ist in
http://groups.google.com/group/comp.lan ... 26af0699b1
Antworten