Python 3 argparse 帮助菜单

Python 3 argparse help menu

为什么当我做一个简单的商店时,它会搞砸帮助菜单?它出于某种原因添加了全部大写的目的地,我不知道如何将其关闭。您可以在下面看到差异。第一个是使用 store_const ,它不会弄乱帮助菜单,但当然不适合我的需要。第二个是简单的商店。看出区别了吗?

常量存储

dev@taco:~/argparse$ python3 arg-0.0.1.py -h
usage: arg-0.0.1.py [-h] [-s] [-e] [-v]

Example list of options

optional arguments:
  -h, --help     show this help message and exit
  -s, --start    enter the starting value
  -e, --end      enter the ending value
  -v, --version  show program's version number and exit

简易商店

dev@taco:~/argparse$ python3 arg-0.0.1.py -h
usage: arg-0.0.1.py [-h] [-s START] [-e END] [-v]

Example list of options

optional arguments:
  -h, --help            show this help message and exit
  -s START, --start START
                        enter the starting value
  -e END, --end END     enter the ending value
  -v, --version         show program's version number and exit

这里是简单和常量的实际代码:

#! /usr/bin/env python3
import argparse
parser = argparse.ArgumentParser(description='Example list of options', add_help=True)
parser.add_argument('-s', '--start', dest='start', action='store_const', const='1', help='enter the starting value')
parser.add_argument('-e', '--end', dest='end', action='store_const', const='1000', help='enter the ending value')
parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.0.1')
results = parser.parse_args()
print ('Starting value = ', results.start)
print ('Ending value = ', results.end)

#! /usr/bin/env python3
import argparse
parser = argparse.ArgumentParser(description='Example list of options', add_help=True)
parser.add_argument('-s', '--start', dest='start', action='store', help='enter the starting value')
parser.add_argument('-e', '--end', dest='end', action='store', help='enter the ending value')
parser.add_argument('-v', '--version', action='version', version='%(prog)s 0.0.1')
results = parser.parse_args()
print ('Starting value = ', results.start)
print ('Ending value = ', results.end)

也许这只是预料之中的,它添加 START 和 END 的原因是告诉用户该标志需要一个参数。它只是有点混乱。此外,由于菜单是自动换行的,因此一开始很难阅读。

如何清理菜单?也许建议一种方法来增加帮助菜单的大小以首先解决自动换行问题,然后如果可能的话,也许还可以将开始和结束更改为更容易理解的其他内容。也许 <value>?

字符串确实是预期参数的占位符,它被称为元变量。使用的字符串由 add_argumentmetavar 关键字参数控制。默认值 (None) 指定所有大写的目标名称。使用空字符串来抑制它,或者通过 任何其他字符串(例如 '<value>')来更改它。

parser.add_argument('-s', '--start',
                     dest='start',
                     action='store',
                     metavar='',
                     help='enter the starting value')