Logan Logan - 3 months ago 12
Python Question

Custom usage message for a single argument in argparse

I have a parameter that can be specified by the user with either one or two arguments:

parser.add_argument("-s", "--start", required=True, metavar='START_TIME',
nargs='+', help="The start time either in milliseconds or as MM/DD/YYYY HH:MM:SS.")


The help message shows this:

usage: foo
-s START_TIME [START_TIME ...]

Foo

optional arguments:
-s START_TIME [START_TIME ...], --start START_TIME [START_TIME ...]
The start time of the query window either in
milliseconds or as MM/DD/YYYY HH:MM:SS (24 hr).


This is somewhat misleading because of the
[START_TIME ...]
part. Is there a way that I can modify the usage message for this one argument so that it shows something more like:

usage: foo
-s START_TIME

Foo

optional arguments:
-s START_TIME, --start START_TIME
The start time of the query window either in
milliseconds or as MM/DD/YYYY HH:MM:SS (24 hr).


I know I can replace the entire usage message with argparse, but I have several other arguments that I don't want to mess with. I would like do do something like `nargs='1|2', but I'm afraid that might be wishful thinking... Other than restructuring my CLI, is there something I can do to fix the usage message for a single parameter? Thanks.

Answer

I suggest removing nargs from your call to add_argument. nargs='+' indicates there may be more than one input for that argument, but in actuality you always want one argument. A string of MM/DD/YYYY HH:MM:SS is one argument conceptually and may be passed in with quotes:

python script.py -s 978370496000
python script.py -s "01/01/2001 12:34:56"

python temp3.py -h
usage: temp3.py [-h] -s START_TIME

optional arguments:
  -h, --help            show this help message and exit
  -s START_TIME, --start START_TIME
                        The start time either in milliseconds or as MM/DD/YYYY
                        HH:MM:SS.

This will produce your desired usage message, and I think will be less confusing to the caller.

Comments