Shivendra Mishra
Shivendra Mishra

Reputation: 688

Reformatting help in python argparse

I want to modify the format of argparse help. Is there a way to do this? This is how it looks like:

-s [SERVER], --server [SERVER]
                    Expects address of server

But I want to change it something like this:

-s, --server <SERVER>  Expects address of server
                       line_2 of help

Is it possible without overriding the whole help manually? or Is there any other pythonic way of doing this?

Upvotes: 3

Views: 417

Answers (2)

Kwydin
Kwydin

Reputation: 67

I was working around a similar problem and here is my solution for it:

parser.add_argument('-s, --server <SERVER>',
                    action='version',
                    # version is only in case someone actually tries to input
                    # '-s, --server <SERVER>' as parameter
                    version='This is a help output only, use -s or --server instead',
                    help="help description for server")

parser.add_argument('-s', '-server', '--server',
                    dest='server',     # to fall under namespace.server
                    type=server_regex, # custom definition to validate input
                    help=argparse.SUPPRESS)

output from such code would be:

optional arguments:
  -h, --help     show this help message and exit
  -s, --server <SERVER>
                 help description for server

Better spacing would require modification of the help formatting, for me this was good enough

Upvotes: 2

Eugene Soldatov
Eugene Soldatov

Reputation: 10135

There is formatter class in argparse to raw output help messages:

argparse.RawTextHelpFormatter

https://docs.python.org/2/library/argparse.html#argparse.RawTextHelpFormatter

parser = argparse.ArgumentParser(
             description='My command',
             formatter_class=argparse.RawTextHelpFormatter)

parser.add_argument("-s", "--server",
                    default='',
                    help="Expects address of server\n line_2 of help")

Upvotes: 1

Related Questions