1

Consider the following sample code

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('action', help='Action to take')
parser.add_argument('-b','--bar', help='Description for bar argument')
parser.parse_args()

The output of calling it with a --help argument would probably be something like this:

positional arguments:

action   Action to take


optional arguments:

-h, --help show this help message and exit
-b  --bar  Description for bar argument

I dont want the above default help text that Argparse generates. I want a message that is entirely written by me

For example calling the file with --help argument should display the following help message:

Please go to http://some_website.com/help to understand more about our software

So how do I provide my custom message to Argparse?

Vinay
  • 699
  • 4
  • 22
  • 1
    I think the following link may help: https://stackoverflow.com/questions/14591168/argparse-dont-show-usage-on-h. You can suppress what you don't want to show and just keep the description. – Dan Perera Aug 06 '19 at 06:06
  • https://stackoverflow.com/questions/45806664/python-argparse-override-help-from-parent?rq=1 – Adiii Aug 06 '19 at 06:48
  • In the default setup, `-h/--help` calls `parser.print_help()` and exits. `print_help` uses `parser.format_help`. You can customize these. From the docs: https://docs.python.org/3/library/argparse.html#printing-help – hpaulj Aug 06 '19 at 07:11
  • https://stackoverflow.com/questions/33906513/argparse-custom-help-from-text-file – hpaulj Aug 06 '19 at 07:18
  • Another option is to look at `sys.argv` before calling `parse_args`. If you see `help` (in some form) print the message and exit. – hpaulj Aug 06 '19 at 23:55

1 Answers1

0

You need to override print_help() method. So, I have created a class called MyArguementParser that overrides ArgumentParser just like so:

import argparse
import sys as _sys

class MyArgumentParser(argparse.ArgumentParser):

    def print_help(self, file=None):
        if file is None:
            file = _sys.stdout
        message = "Please go to http://some_website.com/help to understand more about our software"
        file.write(message+"\n")

Now, instead of called ArgumentParser, you will call MyArgumentParser like so:

parser = MyArgumentParser() #THIS IS THE ONLY CHANGE YOU NEED TO MAKE
# parser = argparse.ArgumentParser()
parser.add_argument('action', help='Action to take')
parser.add_argument('-b','--bar', help='Description for bar argument')
parser.parse_args()

Now, when you run the script using -h or --help flag!

You can also override print_usage() the same way to show the same message when the user misuses any of the provided arguments.

Anwarvic
  • 12,156
  • 4
  • 49
  • 69