45

I am trying to learn how to use python's argparse module. Currently my python script is:

parser = argparse.ArgumentParser(description='My first argparse attempt',
                                add_help=True)
parser.add_argument("-q", action ="store", dest='argument',
                    help="First argument")
output = parser.parse_args()

And it gives the output as :

usage: test.py [-h] [-q ARGUMENT]

My first argparse attempt

optional arguments:
  -h, --help   show this help message and exit
  -q ARGUMENT  First argument

Now, lets suppose I want my -h or --help argument to print a usage example also. Like,

   Usage: python test.py -q "First Argument for test.py"

My purpose is to print the above usage example along with the default content of -h argument so that the user can get a basic idea of how to use the test.py python script.

So, is this functionality inbuilt in the argparse module. If no than what is the correct way to approach this problem.

RanRag
  • 48,359
  • 38
  • 114
  • 167

1 Answers1

57

Use parser.epilog to display something after the generated -h text.

parser = argparse.ArgumentParser(
    description='My first argparse attempt',
    epilog='Example of use')

output = parser.parse_args()

prints:

My first argparse attempt

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

Example of use
georg
  • 211,518
  • 52
  • 313
  • 390
  • 28
    @Noob -- Note that whitespace will be stripped from your description and epilog (which is often not good for "Examples of Use". To allow that you want the `argparse.RawDescriptionHelpFormatter` ( http://docs.python.org/dev/library/argparse.html#argparse.RawDescriptionHelpFormatter ) – mgilson Jun 07 '12 at 11:56
  • 6
    Is there a way to use argparse.RawDescriptionHelpFormatter just for the epilog and not for the description? I want the description to be wrapped automatically. but I want to take care of the formatting of epilogue. – user2015487 Nov 07 '16 at 06:05
  • Please add note about `RawDescriptionHelpFormatter` so that we can +1 this answer. – yugr May 09 '20 at 02:58