简体   繁体   中英

How to change the format of subparser with argparse

I know there is max_help_position for the main parser created with the constructor but how to change subparsers format since I have some times very long command name and I want the help message to be aligned with it.

#!/usr/bin/env python

import argparse
import subprocess

parser = argparse.ArgumentParser(description="example",
                                 formatter_class=argparse.RawDescriptionHelpFormatter)

subparsers = parser.add_subparsers(title="available commands",metavar="command [options ...]")

parser1 = subparsers.add_parser('short-cmd', help='help message')
parser1.add_argument('--path')

parser2 = subparsers.add_parser('very-long-long-name-for-a-command', help='help message')
parser2.add_argument('--path')

args = parser.parse_args()

output :

usage: test.py [-h] command [options ...] ...

example

optional arguments:
  -h, --help            show this help message and exit

available commands:
  command [options ...]
    short-cmd           create a directory for database
    very-long-long-name-for-a-command
                        create a directory for database

what i want :

usage: test.py [-h] command [options ...] ...

example

optional arguments:
  -h, --help            show this help message and exit

available commands:
  command [options ...]
    short-cmd                          create a directory for database
    very-long-long-name-for-a-command  create a directory for database

You correctly note that there is a max_help_position that controls the indent for help lines. The default value in the HelpFormatter __init__ is 24 .

But the trick is to change that.

One way is to subclass HelpFormatter (or the Raw... one if you need that).

class MyFormatter(argparse.HelpFormatter):
    def __init__(self,prog):
        super(MyFormatter,self).__init__(prog,max_help_position=55)
parser=argparse.ArgumentParser(formatter_class=MyFormatter)

In theory you could create or modify a formatter with:

formatter = argparse.HelpFormatter(`prog`, max_help_position=40)

or

formatter = argparse.HelpFormatter('prog')
formatter._max_help_position = 45

But to do that you'd have to tweak some place within this calling tree:

`-h`
parser.print_help()
    parser.format_help()
        parser._get_formatter()
            parser.formatter_class(prog=self.prog)

(check my edit history if you think I removed something useful).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM