Custom help format for a choice argparse argument
Weatherby,Gerard
gweatherby at uchc.edu
Fri Jan 27 16:22:47 EST 2023
Why not something like:
parser.add_argument("-z", "--zone")
args = parser.parse_args()
if args.zone and args.zone not in ptyz.all_timezones:
print(“Invalid timezone”,file=sys.stderr)
…
From: Python-list <python-list-bounces+gweatherby=uchc.edu at python.org> on behalf of Ivan "Rambius" Ivanov <rambiusparkisanius at gmail.com>
Date: Friday, January 27, 2023 at 3:33 PM
To: Python <python-list at python.org>
Subject: Custom help format for a choice argparse argument
*** Attention: This is an external email. Use caution responding, opening attachments or clicking on links. ***
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?
Regards
rambius
--
Tangra Mega Rock: https://urldefense.com/v3/__http://www.radiotangra.com__;!!Cn_UX_p3!kiJusdm5pCptP3sOBX85KXqUJkqr2jSa4C_-WAqND7WkL-aw3BYbW50td_AcuzJ1XUPYIVO3JiLMc4gRWS885vTKFsFvaQ$<https://urldefense.com/v3/__http:/www.radiotangra.com__;!!Cn_UX_p3!kiJusdm5pCptP3sOBX85KXqUJkqr2jSa4C_-WAqND7WkL-aw3BYbW50td_AcuzJ1XUPYIVO3JiLMc4gRWS885vTKFsFvaQ$>
--
https://urldefense.com/v3/__https://mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!kiJusdm5pCptP3sOBX85KXqUJkqr2jSa4C_-WAqND7WkL-aw3BYbW50td_AcuzJ1XUPYIVO3JiLMc4gRWS885vRXq-JKLg$<https://urldefense.com/v3/__https:/mail.python.org/mailman/listinfo/python-list__;!!Cn_UX_p3!kiJusdm5pCptP3sOBX85KXqUJkqr2jSa4C_-WAqND7WkL-aw3BYbW50td_AcuzJ1XUPYIVO3JiLMc4gRWS885vRXq-JKLg$>
More information about the Python-list
mailing list