Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse: Preformatted help text?

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?

like image 752
petraus Avatar asked Dec 07 '10 09:12

petraus


2 Answers

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)
like image 137
user225312 Avatar answered Oct 14 '22 21:10

user225312


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.

like image 33
Anthon Avatar answered Oct 14 '22 21:10

Anthon