python - argparse 中单个参数的自定义使用消息

标签 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 之外,我还能做些什么来修复单个参数的使用消息?谢谢。

最佳答案

我建议从您对 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.

这将产生您想要的使用消息,我认为调用者不会那么困惑。

关于python - argparse 中单个参数的自定义使用消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39048139/

相关文章:

python - 如何从命名空间中删除参数

python - nargs > 1 的位置参数的元组元变量值

python - 在 Python 中将 3 个单独的 numpy 数组组合为 RGB 图像

python - Google App Engine NDB 数据库损坏了吗?

python - OpenCV(4.2.0)错误:(-215:断言失败)函数 'cv::imshow'中的size.width> 0 && size.height> 0

python - argparse - 列表/元组的可选参数

Python argparse : type inconsistencies when combining 'choices' , 'nargs' 和 'default'

python - 有没有办法在 python 中指定一个包中所有脚本都可用的 BASE_DIR 设置?

python - Golang的TLE(超过时间限制)错误,但使用类似逻辑的Python则没有。但为什么?

c++ - 是否可以从 C++ 中删除在 Python 中分配的对象?