您可以使您的格式化程序类以您想要的任何方式格式化参数。这并不完全直截了当,但这是产生以下输出的输出(假设@mgilson 是正确的,假设您只想为一组命令名称显示一次元变量......否则只需指定一个实际值metavar='value'
,它将显示正是那个文本。):
# without metavar specified:
-c, --chunksize CHUNKSIZE
chunk size in bits
# with metavar specified:
-c, --chunksize some_metavar
chunk size in bits
以及该类的代码并重现两个输出:
import argparse
# 2.7-3.2
class SingleMetavarHelpFormatter(argparse.HelpFormatter):
def _format_action_invocation(self, action):
if not action.option_strings:
metavar, = self._metavar_formatter(action, action.dest)(1)
return metavar
else:
parts = []
# if the Optional doesn't take a value, format is:
# -s, --long
if action.nargs == 0:
parts.extend(action.option_strings)
# if the Optional takes a value, format is:
# -s ARGS, --long ARGS
else:
default = action.dest.upper()
args_string = self._format_args(action, default)
## THIS IS THE PART REPLACED
#~ for option_string in action.option_strings:
#~ parts.append('%s %s' % (option_string, args_string)) ### this is change
## /SECTION REPLACED
## NEW CODE:
parts.extend(action.option_strings)
parts[-1] += ' %s' % args_string
## /NEW CODE
return ', '.join(parts)
parser = argparse.ArgumentParser(
prog='PROG',
formatter_class=SingleMetavarHelpFormatter
)
parser.add_argument('-c', '--chunksize', type=int, help='no metavar specified')
parser.add_argument('-w', '--with_metavar', type=int, help='metavar specified', metavar='some_metavar')
parser.print_help()
编辑:
根本不显示元变量,您可以将一个空字符串传递给元变量:
parser.add_argument('-e', '--with_empty_metavar', type=int, help='empty metavar specified', metavar='')
使用原始类和新类执行此操作的区别在于短命令语法后缺少额外的空格字符。
#usage: PROG [-h] [-c CHUNKSIZE] [-w some_metavar] [-e]
#
#optional arguments:
# -h, --help show this help message and exit
# -c CHUNKSIZE, --chunksize CHUNKSIZE
# no metavar specified
# -w some_metavar, --with_metavar some_metavar
# metavar specified
# -e, --with_empty_metavar
# empty metavar specified