Pergunta

I'm using argparse and I want to display a list in the help text of one of my options. However, argparse strips new lines from the text and displays it on a single line.

Is there anyway to tell argparse that the help string is preformatted, and not to strip new line characters?

Foi útil?

Solução

From the docs:

RawTextHelpFormatter maintains whitespace for all sorts of help text including argument descriptions.

from argparse import RawTextHelpFormatter
parser = ArgumentParser(description='test', formatter_class=RawTextHelpFormatter)

Outras dicas

If you just want to override the one option, you cannot use RawTextHelpFormatter. Instead subclass the HelpFormatter and provide a special intro for the options that should be handled "raw" (I use "R|rest of help"):

import argparse

class SmartFormatter(argparse.HelpFormatter):

    def _split_lines(self, text, width):
        # this is the RawTextHelpFormatter._split_lines
        if text.startswith('R|'):
            return text[2:].splitlines()  
        return argparse.HelpFormatter._split_lines(self, text, width)

And use it:

from argparse import ArgumentParser
from textwrap import dedent

parser = ArgumentParser(description='test')

parser.add_argument('--list', help=dedent("""\
    R|abc
      def
        ghi
"""))
parser.parse_args()

Any other calls to .add_argument() where the help does not start with R| will be wrapped as normal.

This is part of my improvements on argparse. The full SmartFormatter also supports adding the defaults to all options, and raw input of the utilities description.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top