argparse

时间:2016-08-19 21:49:44

标签: python argparse

我有一个参数可以由用户用一个或两个参数指定:

parser.add_argument("-s", "--start", required=True, metavar='START_TIME', 
  nargs='+', help="The start time either in milliseconds or as MM/DD/YYYY HH:MM:SS.")

帮助信息显示:

usage: foo
   -s START_TIME [START_TIME ...]

Foo

optional arguments:
  -s START_TIME [START_TIME ...], --start START_TIME [START_TIME ...]
                    The start time of the query window either in
                    milliseconds or as MM/DD/YYYY HH:MM:SS (24 hr).

由于[START_TIME ...]部分,这有点误导。有没有办法可以修改这个参数的用法消息,以便它显示更像:

usage: foo
   -s START_TIME

Foo

optional arguments:
  -s START_TIME, --start START_TIME
                    The start time of the query window either in
                    milliseconds or as MM/DD/YYYY HH:MM:SS (24 hr).

我知道我可以用argparse替换整个用法消息,但我还有其他几个我不想搞砸的论点。我想做'nargs =' 1 | 2'之类的事情,但我担心这可能是一厢情愿的想法......除了重构我的CLI之外,还有什么我可以做的来修复单个参数的用法消息?谢谢。

3 个答案:

答案 0 :(得分:2)

我建议您从nargs的电话中删除add_argumentnargs='+'表示该参数可能有多个输入,但实际上您总是需要一个参数。一个MM/DD/YYYY HH:MM:SS字符串在概念上是一个参数,可以用引号传递:

python script.py -s 978370496000
python script.py -s "01/01/2001 12:34:56"

python temp3.py -h
usage: temp3.py [-h] -s START_TIME

optional arguments:
  -h, --help            show this help message and exit
  -s START_TIME, --start START_TIME
                        The start time either in milliseconds or as MM/DD/YYYY
                        HH:MM:SS.

这将产生您想要的使用信息,我认为不会让来电者感到困惑。

答案 1 :(得分:1)

table-footer-group标志的默认显示为'+'。它应该传达这样的想法,即你必须给出至少一个值,但可以有更多。 (看看S [S ...]生成的内容。)

*

在您的情况下,In [306]: parser=argparse.ArgumentParser() In [307]: a1=parser.add_argument('-s',nargs='+') In [308]: parser.print_help() usage: ipython3 [-h] [-s S [S ...]] optional arguments: -h, --help show this help message and exit -s S [S ...] 字符串只是替换了从metavar派生的默认字符串。

你可以给出一个元组元变量,它显示为:

dest

空元变种:

In [309]: a1.metavar=('A','B')
In [310]: parser.print_help()
usage: ipython3 [-h] [-s A [B ...]]

optional arguments:
  -h, --help    show this help message and exit
  -s A [B ...]

覆盖此格式

In [312]: parser.print_help()
usage: ipython3 [-h] [-s  [...]]

optional arguments:
  -h, --help  show this help message and exit
  -s  [ ...]

您必须使用修改后的'%s [%s ...]' % get_metavar(2) 方法创建自定义HelpFormatter子类。

=================

至于_format_args我已经探讨了添加以nargs='1|2'语法为模型的范围选项。添加起来并不难,但您必须熟悉regex代码。关于该主题存在Python错误/问题。

答案 2 :(得分:-2)

如果您想拥有零个,一个或两个参数而不是更多,则可以有两个选项-s1-s2

用户可以更清楚或更清楚地了解应用程序的用法。