Python argparse - help text for long argument name

Python 'argparse' display help text on a new line for a long named argument :

**#script.py -h

Select one of the options given


optional arguments:
  -h, --help            show this help message and exit
  -bs , --business_service 
                        choose the service     << New line
  -so , --service_offering 
  -ci , --cmdb_ci       provide configuration item
  -desc , --description 
                        write description     << New line

Below is the code I'm using:

self.parser = argparse.ArgumentParser(
            description='Select one of the options given',
            epilog=self._get_usage(),
            formatter_class=argparse.RawTextHelpFormatter
            )


        self.parser.add_argument('-bs','--business_service',type=str,help='choose the service',metavar='')
        self.parser.add_argument('-so','--service_offering',type=str,metavar='')
        self.parser.add_argument('-ci','--mdcb_ci',type=str,help='provide configuration item',metavar='')
        self.parser.add_argument('-desc','--description',type=str,help='write description',metavar='')

I want the help string to be on the same line of the argument :

-bs , --business_service     choose the service     << Same line

How can I solve it?

Upvotes: 3

Views: 1588

Answers (1)

hpaulj
hpaulj

Reputation: 231395

The HelpFormatter class takes a max_help_position argument. The default value is 24, which is what you are seeing in the help.

It can be changed with a new Formatter subclass, or modification to the calling argument.

In [23]: parser.formatter_class = 
    lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=30)

Here I'm modifying the formatter_class attribute after, but you could instead use this lambda line in place of

formatter_class=argparse.RawTextHelpFormatter

The result is:

In [24]: parser.print_help()
usage: ipython3 [-h] [-bs] [-so] [-ci] [-desc]

Select one of the options given

optional arguments:
  -h, --help                 show this help message and exit
  -bs , --business_service   choose the service
  -so , --service_offering 
  -ci , --mdcb_ci            provide configuration item
  -desc , --description      write description

Parameters like this were chosen to balance overall width of the display with legibility. They can be tweaked like this, but it does require some Python programming knowledge. It's been a while since I did this, so my suggestion might not be the simplest. But it's generally in the right direction.

Another way of setting it with the partial wrapper:

In [42]: from functools import partial
In [43]: newformatter=partial(argparse.HelpFormatter, max_help_position=30)
In [44]: parser.formatter_class=newformatter

Upvotes: 5

Related Questions