argparse 中单个参数的自定义用法消息

Custom usage message for a single argument in 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 之外,我还能做些什么来修复单个参数的使用消息?谢谢。

我建议从您对 add_argument 的通话中删除 nargsnargs='+' 表示该参数可能有多个输入,但实际上您总是需要一个参数。 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.

这将生成您想要的用法消息,我认为调用者不会感到困惑。

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

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

'+' nargs 的默认显示是 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)

您必须使用修改后的 _format_args 方法创建自定义 HelpFormatter 子类。

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

至于 nargs='1|2',我探索了添加一个以 regex 语法为模型的范围选项。添加并不难,但是你必须熟悉 argparse.py 代码。有一个 Python bug/issue 关于这个话题。