Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 560
Shivendra Mishra Avatar asked Jul 10 '26 19:07

Shivendra Mishra


2 Answers

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

like image 82
Kwydin Avatar answered Jul 13 '26 11:07

Kwydin


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")
like image 30
Eugene Soldatov Avatar answered Jul 13 '26 10:07

Eugene Soldatov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!