How to modify the metavar for a positional argument in pythons argparse?

≯℡__Kan透↙ 提交于 2019-11-30 17:37:13

How about:

import argparse
if __name__ == '__main__':
    parser = argparse.ArgumentParser(description = "Print a range.")

    parser.add_argument("start", type = int, help = "Specify start.", )
    parser.add_argument("stop", type = int, help = "Specify stop.", )
    parser.add_argument("step", type = int, help = "Specify step.", )

    args=parser.parse_args()
    print(args)

which yields

% test.py -h
usage: test.py [-h] start stop step

Print a range.

positional arguments:
  start       Specify start.
  stop        Specify stop.
  step        Specify step.

optional arguments:
  -h, --help  show this help message and exit

However, if I change the optional -range1 argument to a positional range1 argument, argparse cannot deal with the tuple of the metavar parameter (ValueError: too many values to unpack).

argparse shouldn't be giving that too many values to unpack error message. It's produced by metavar, = self._metavar_formatter(action, default)(1). Normally this function produces a single item list or tuple, but in your case it returns the tuple metavar. It needs to give a more informative error message (tuple metavar not allowed with positionals ?), or gracefully adapt the metavar (start|stop|step ?). Another option is to use the default metavar in the help line instead of the tuple.

The tuple metavar works ok on the usage line.

I think the help formatting was written with uniform positionals in mind. On the usage line it might show X [X [X ...]], but on the help line just X ... description of X.

Your 3 items have distinct names, so unutbu's suggestion of 3 separate positionals is probably what the argparse designers had in mind.

This issue has been raised (but not patched)

http://bugs.python.org/issue14074 "argparse allows nargs>1 for positional arguments but doesn't allow metavar to be a tuple"

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!