Search code examples
pythonargparseusage-message

Python Argparse Adding Text To Usage Message


I am working on a small Python program that needs to get some command line parameters and use argparse to display usage message . I have these 2 lines

parser.add_argument("-r",type=int,default=1)
parser.add_argument("-c",type=int,default=2)

And the requirement is that I show the user this message :

*usage: myprogram.py [-h]  [-r ROWS] [-c COLUMNS]* 

However what I show the user is -

*usage: myprogram.py [-h] [-r R] [-c C]*

How can I turn [-r R] into [-r ROW] (and in the same manner [-c C] to [-c COLUMNS])?

I have looked at the argsparse docs quite a bit with no avail...


Solution

  • Use the metavar parameter:

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("-r", type=int, default=1, metavar='ROWS')
    parser.add_argument("-c", type=int, default=2, metavar='COLUMNS')
    args = parser.parse_args()
    

    Then, python test.py -h yields

    usage: test.py [-h] [-r ROWS] [-c COLUMNS]
    
    optional arguments:
      -h, --help  show this help message and exit
      -r ROWS
      -c COLUMNS