Custom help format for a choice argparse argument

Thomas Passin list1 at tompassin.net
Fri Jan 27 18:21:47 EST 2023


On 1/27/2023 4:53 PM, Ivan "Rambius" Ivanov wrote:
> Hello Cameron,
> 
> On Fri, Jan 27, 2023 at 4:45 PM Cameron Simpson <cs at cskk.id.au> wrote:
>>
>> On 27Jan2023 15:31, Ivan "Rambius" Ivanov <rambiusparkisanius at gmail.com> wrote:
>>> I am developing a script that accepts a time zone as an option. The
>>> time zone can be any from pytz.all_timezones. I have
>>>
>>> def main():
>>>     parser = argparse.ArgumentParser()
>>>     parser.add_argument("-z", "--zone", choices=pytz.all_timezones)
>> [...]
>>>
>>> It works, but when I run it with the -h option it dumps all entries in
>>> pytz.all_timezones.
>>
>> What happens if you just presupply a `help=` parameter in
>> `add_argument`?
> 
> I tried with def main():
>      parser = argparse.ArgumentParser()
>      parser.add_argument("-z", "--zone", choices=pytz.all_timezones,
> help="a timezone from pytz.all_timezones")
>      args = parser.parse_args()
>      print(args)
> 
> -h still shows all the contents of pytz.all_timezones.
> 

Adding a few arguments makes it work (with the help of the argparse doc 
page and Stack Overflow:
 
https://stackoverflow.com/questions/14950964/overriding-default-argparse-h-behaviour):

import argparse
import pytz

HELP ="""\nThis is the help message.
This is the second line of the help message."""

def main():
     parser = argparse.ArgumentParser(add_help=False, usage = HELP)
     parser.add_argument("-z", "--zone", choices=pytz.all_timezones,
                         help = argparse.SUPPRESS)
     parser.add_argument('-h', '--h', action = 'help',
                         help = argparse.SUPPRESS)
     args = parser.parse_args()
     print(args)
     print(f"Specified timezone: {args.zone}")


main()

Your help message will display after "usage", like this -

usage:
This is the help message.
This is the second line of the help message.

You would give up have argparse automatically list all the options, but 
you can add add them manually to the HELP string.




More information about the Python-list mailing list