您可以将ArgumentDefaultsHelpFormatter子类化以执行所需的操作。
from argparse import ArgumentDefaultsHelpFormatter,RawDescriptionHelpFormatter
class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter):
def _get_help_string(self, action):
help = action.help
if '%(default)' not in action.help:
if action.default is not argparse.SUPPRESS:
defaulting_nargs = [argparse.OPTIONAL, argparse.ZERO_OR_MORE]
if action.option_strings or action.nargs in defaulting_nargs:
if type(action.default) == type(sys.stdin):
print action.default.name
help += ' (default: ' + str(action.default.name) + ')'
else:
help += ' (default: %(default)s)'
return help
parser = argparse.ArgumentParser(prog='PROG', formatter_class=CustomFormatter)
对我来说结果是:
optional arguments: -h, --help show this help message and exit --infile File, -i File The input file/stream. (default:) --outfile File, -o File The output file/stream. (default: ) --whatever-arg WHATEVER_ARG, -w WHATEVER_ARG Change something (default: any)