4

Currently I am using the following code to initialize my ArgumentParser:

parser = argparse.ArgumentParser(description="Help line 1\n" +
                                             "Help line 2",
                                 formatter_class=argparse.RawTextHelpFormatter)

Which, after adding some arguments, gives me the following output:

/usr/bin/python3.6 /data/Poseidon/dev/Python/trident.py -h
usage: trident.py [-h] [--verbose] [--images] --source SOURCE --network
                  NETWORK

Help line 1
Help line 2

I would rather not have the "NETWORK" argument in the "usage" part of the help output in the next line, but on the same line. Is there any way to tell argparse to not add newlines in the list of arguments?

Matthias
  • 9,817
  • 14
  • 66
  • 125

2 Answers2

8

Try this:

parser = argparse.ArgumentParser(description="Help line 1\n" +
                                             "Help line 2",
                                 formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999))

If you do this, take note of this comment from HelpFormatter.__doc__:

Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail.

0x5453
  • 12,753
  • 1
  • 32
  • 61
  • 1
    Thanks, that did the trick for me. As for the records, according to [this answer](https://stackoverflow.com/a/29613565/514149), another way to achieve this is to the set the `COLUMNS` environment variable. – Matthias Nov 13 '18 at 14:47
0

The better resolution (comparing to https://stackoverflow.com/a/53283500/10418734) is

  1. Create a class that formats with a desired width
class _WidthFormatter(argparse.RawTextHelpFormatter):
    def __init__(self, prog: Text) -> None:
        super().__init__(prog, width=99999)
  1. And use the class
parser = argparse.ArgumentParser(
    description=(
        "Help line 1\n"
        "Help line 2"
    ),
    formatter_class= _WidthFormatter
)

This solution is preferred as formatter_class argument in argparse.ArgumentParser expects to use a class, not a class instance.

Dmytro Serdiuk
  • 859
  • 10
  • 20