如何在pythons argparse中修改位置参数的元变量? [英] How to modify the metavar for a positional argument in pythons argparse?

查看:38
本文介绍了如何在pythons argparse中修改位置参数的元变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

argparse 包中,metavar 参数修改程序显示的帮助信息.下面的程序并不打算运行,它只是用来演示 metavar 参数的行为.

In the argparse package the metavar parameter modifies the displayed help message of a program. The following program is not intended to work, it is simply used to demonstrate the behavior of the metavar parameter.

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

    parser.add_argument("-range1", nargs = 3, type = int, help = "Specify range with: start, stop, step.", metavar = ("start", "stop", "step"))
    parser.add_argument("-range2", nargs = 3, type = int, help = "Specify range with: start, stop, step.", metavar = "r2")

对应的帮助信息为:

usage: main.py [-h] [-range1 start stop step] [-range2 r2 r2 r2]

Print a range.

optional arguments:
  -h, --help            show this help message and exit
  -range1 start stop step
                        Specify range with: start, stop, step.
  -range2 r2 r2 r2      Specify range with: start, stop, step.

请注意-range1-range2 背后的区别.显然 -range1 是帮助消息的首选方式.

Please note the differences behind -range1 and -range2. Clearly -range1 is the preferred way of the help message.

到目前为止,一切对我来说都很清楚.但是,如果我将可选的 -range1 参数更改为位置 range1 参数,argparse 将无法处理 metavar<的元组/code> 参数(ValueError:解包的值太多).
我能够让它工作的唯一方法是 -range2 完成的方式.但是帮助信息远不如 -range1 的情况.

Up to this point everything is clear to me. 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).
The only way I was able to get it work was in the way -range2 is done. But then the help message is by far not as good as for the -range1 case.

有没有办法获得与 -range1 情况相同的帮助消息,但使用位置参数而不是可选参数?

Is there a way to get the same help message as for the -range1 case but for a positional argument instead of an optional?

推荐答案

怎么样:

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)

产生的结果

% 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

这篇关于如何在pythons argparse中修改位置参数的元变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆