On 27/01/2023 21:31, Ivan "Rambius" Ivanov wrote:
Hello,

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)
     args = parser.parse_args()
     print(args)
     print(f"Specified timezone: {args.zone}")

It works, but when I run it with the -h option it dumps all entries in
pytz.all_timezones. I would like to modify the help format for just
-z|--zone option. I read the docs about HelpFormatter and argparse.py
and I ended up with

class CustomHelpFormatter(argparse.HelpFormatter):
     def _metavar_formatter(self, action, default_metavar):
         if action.dest == 'zone':
             result = 'zone from pytz.all_timezones'
             def format(tuple_size):
                 if isinstance(result, tuple):
                     return result
                 else:
                     return (result, ) * tuple_size
             return format
         else:
             return super(CustomHelpFormatter,
self)._metavar_formatter(action, default_metavar)


def main():
     parser = argparse.ArgumentParser(formatter_class=CustomHelpFormatter)
     parser.add_argument("-z", "--zone", choices=pytz.all_timezones)
     args = parser.parse_args()
     print(args)
     print(f"Specified timezone: {args.zone}")

This works, but is there a more elegant way to achieve it?

It may be sufficient to specify a metavar:

>>> import argparse
>>> p = argparse.ArgumentParser()
>>> p.add_argument("--foo", choices="alpha beta gamma".split(),
metavar="<any greek letter>")
[...]
>>> p.parse_args(["-h"])
usage: [-h] [--foo <any greek letter>]

optional arguments:
  -h, --help            show this help message and exit
  --foo <any greek letter>

While that helps with --help it doesn't always prevent the choices list
from being spelt out:

>>> p.parse_args(["--foo", "whatever"])
usage: [-h] [--foo <any greek letter>]
: error: argument --foo: invalid choice: 'whatever' (choose from
'alpha', 'beta', 'gamma')

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to