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

问题描述

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参数(ValueError: too many values to unpack)的元组.我能够使它工作的唯一方法是完成-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中修改位置参数的metavar?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 16:14