Python argparse: formatted help text?

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

Is there anyway to tell argparse that the help line is pre-formatted, and not for a strip of new line characters?

+4
source share
2 answers

From docs :

RawTextHelpFormatter supports a space for all kinds of help including argument descriptions.

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

If you just want to override one parameter, you cannot use RawTextHelpFormatter . Instead, subclass HelpFormatter and provide a special introduction for the parameters that should be processed "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 help does not start with R| will be wrapped as usual.

This is part of my argparse improvements . Full SmartFormatter also supports adding default values ​​for all parameters and the initial input of the utility description.

+3
source

All Articles