我有一个参数,用户可以使用一个或两个参数指定该参数:
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
的调用中删除 nargs
。 nargs='+'
表示该参数可能有多个输入,但实际上您总是需要一个参数。一串 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/