0

Is there a way to control the whitespace of the help-text that argparse prints to stdout?

The example help-text at https://docs.python.org/3/howto/argparse.html are all short, and I couldn't find any verbiage describing how to handle formatting for long strings.

The only thing that came to mind was "\n" - but base on my attempt, that seems to be stripped outright:

#! /usr/bin/python3

import argparse
import json

def parseArgs():
    """
    To learn argparse.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('--json_args', required = False, nargs = '?',
                        default = '{}',
                        help = """JSON-encapsulated key/value optargs\n
                        e.g. {"foo": "bar"}
                        """
                        )
    a, _ = parser.parse_known_args()
    j = json.loads(a.json_args)
    r = {}
    r['secret'] = 'open_sesame'

    for k, v in j.items():
        r[k.lower()] = v

    return r

def main():
    args = parseArgs()
    print(json.dumps(args))

if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        print(e)
        sys.exit(1)
$ python3 ./a.py --help
usage: a.py [-h] [--json_args [JSON_ARGS]]

optional arguments:
  -h, --help            show this help message and exit
  --json_args [JSON_ARGS]
                        JSON-encapsulated key/value optargs e.g. {"foo":
                        "bar"}
StoneThrow
  • 5,314
  • 4
  • 44
  • 86
  • 2
    See https://docs.python.org/3/library/argparse.html#argparse.RawTextHelpFormatter – wim Nov 23 '21 at 23:11
  • There are several `raw` formatters. And there is a final formatting step that removes excess nl. – hpaulj Nov 24 '21 at 00:26
  • This might also help, https://stackoverflow.com/questions/46554084/how-to-reduce-indentation-level-of-argument-help-in-argparse – hpaulj Nov 24 '21 at 05:55

1 Answers1

0

You can override HelpFormatter:

import argparse


class CustomHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
    def __init__(self, *args, **kwargs):
        kwargs["max_help_position"] = 30  # default to 24
        kwargs["width"] = 80  # default to _shutil.get_terminal_size().columns
        super().__init__(*args, **kwargs)



parser = argparse.ArgumentParser(formatter_class=CustomHelpFormatter)
parser.add_argument(
    "--json_args",
    required=False,
    nargs="?",
    default="{}",
    help='JSON-encapsulated key/value optargs e.g. {"foo": "bar"}',
)


parser.print_help()

This gives the result:

usage: arg.py [-h] [--json_args [JSON_ARGS]]

optional arguments:
  -h, --help               show this help message and exit
  --json_args [JSON_ARGS]  JSON-encapsulated key/value optargs e.g. {"foo":
                           "bar"} (default: {})

But be careful, according to python sources:

class HelpFormatter(object):
    """Formatter for generating usage messages and argument help strings.

    Only the name of this class is considered a public API. All the methods
    provided by the class are considered an implementation detail.
    """
Balaïtous
  • 826
  • 6
  • 9