def __init__(self, prog, indent_increment=2, max_help_position=32,
width=None):
super(HelpFormatter, self).__init__(prog, indent_increment,
max_help_position, width)
python类HelpFormatter()的实例源码
def start_section(self, heading):
# Title-case the headings
heading = '%s%s' % (heading[0].upper(), heading[1:])
super(HelpFormatter, self).start_section(heading)
def error(self, error):
"""raise errors instead of printing and raising SystemExit"""
raise self.ArgumentError(error)
#def __init__(self, *args, **kwargs):
# kwargs["formatter_class"] = MyHelpFormatter
# argparse.ArgumentParser.__init__(self, *args, **kwargs)
#class MyHelpFormatter(argparse.HelpFormatter):
# pass
def test_get_base_parser(self):
"""Verify how we construct our basic Argument Parser."""
with mock.patch('argparse.ArgumentParser') as ArgumentParser:
parser = self.shell.get_base_parser()
self.assertEqual(ArgumentParser.return_value, parser)
ArgumentParser.assert_called_once_with(
prog='craton',
description=('Main shell for parsing arguments directed toward '
'Craton.'),
epilog='See "craton help COMMAND" for help on a specific command.',
add_help=False,
formatter_class=argparse.HelpFormatter,
)
def _split_lines(self, text, width):
if text.startswith(RAW_TEXT_ID):
return text[len(RAW_TEXT_ID):].splitlines()
# this is the RawTextHelpFormatter._split_lines
return argparse.HelpFormatter._split_lines(self, text, width)
def __init__(self, *args, **kwargs):
argparse.HelpFormatter.__init__(self, *args, **kwargs)
self._action_max_length = 18
def parse_arguments():
"""
Parse the command line, and check if arguments are correct
"""
# Initiate argument parser
parser = DefaultHelpParser(description='Program description',
# to precisely format help display
formatter_class=lambda prog: argparse.HelpFormatter(prog, width=120, max_help_position=80))
# Main parameters
group_main = parser.add_argument_group('Main parameters')
# -i / --input_sam
group_main.add_argument('-i', '--input_sam',
action = 'store',
metavar = 'INSAM',
type = argparse.FileType('r'),
default = '-',
help = 'Input sam file, sorted by subject and position')
# -o / --output_sam
group_main.add_argument('-o', '--output_sam',
action = 'store',
metavar = 'OUTSAM',
type = argparse.FileType('w'),
default = '-',
help = 'Output sam file')
# -v / --verbose
group_main.add_argument('-v', '--verbose',
action = 'store_true',
help = 'Increase verbosity')
# Debug
group_debug = parser.add_argument_group('Debug parameters')
# --debug
group_debug.add_argument('--debug',
action = 'store_true',
help = 'Output debug infos')
args = parser.parse_args()
#
return args
def _split_lines(self, text, width):
if text.startswith('D|'):
self._add_defaults = True
text = text[2:]
elif text.startswith('*|'):
text = text[2:]
if text.startswith('R|'):
return text[2:].splitlines()
return argparse.HelpFormatter._split_lines(self, text, width)
def _get_help_string(self, action):
if self._add_defaults is None:
return argparse.HelpFormatter._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:
help += ' (default: %(default)s)'
return help
def start_section(self, heading):
# Title-case the headings
heading = '%s%s' % (heading[0].upper(), heading[1:])
super(HelpFormatter, self).start_section(heading)
def test_parser(self):
parser = argparse.ArgumentParser(prog='PROG')
string = (
"ArgumentParser(prog='PROG', usage=None, description=None, "
"version=None, formatter_class=%r, conflict_handler='error', "
"add_help=True)" % argparse.HelpFormatter)
self.assertStringEqual(parser, string)
# ===============
# Namespace tests
# ===============
def _split_lines(self, text, width):
if text.startswith('R|'):
return text[2:].splitlines()
# this is the RawTextHelpFormatter._split_lines
return argparse.HelpFormatter._split_lines(self, text, width)
def test_parser(self):
parser = argparse.ArgumentParser(prog='PROG')
string = (
"ArgumentParser(prog='PROG', usage=None, description=None, "
"formatter_class=%r, conflict_handler='error', "
"add_help=True)" % argparse.HelpFormatter)
self.assertStringEqual(parser, string)
# ===============
# Namespace tests
# ===============
def test_parser(self):
parser = argparse.ArgumentParser(prog='PROG')
string = (
"ArgumentParser(prog='PROG', usage=None, description=None, "
"version=None, formatter_class=%r, conflict_handler='error', "
"add_help=True)" % argparse.HelpFormatter)
self.assertStringEqual(parser, string)
# ===============
# Namespace tests
# ===============
def _split_lines(self, text, width):
# this is the RawTextHelpFormatter._split_lines
if text.startswith('R|'):
return text[2:].splitlines()
return argparse.HelpFormatter._split_lines(self, text, width)
def __init__(self,
prog=None,
usage=None,
description=None,
epilog=None,
parents=[],
formatter_class=argparse.HelpFormatter,
prefix_chars='-',
fromfile_prefix_chars=None,
argument_default=None,
conflict_handler='error',
add_help=True,
allow_abbrev=True):
super(ArgumentParser, self).__init__(
prog,
usage,
description,
epilog,
parents,
formatter_class,
prefix_chars,
fromfile_prefix_chars,
argument_default,
conflict_handler,
add_help,
allow_abbrev)
self.register('action', 'store_dict', _StoreDictAction)
self.register('action', 'store_dict_const', _StoreDictConstAction)
def _init_parser(self, **kwargs):
_def = self._def
num_groups = len(_def.groups)
if num_groups == 0:
raise RuntimeError("At least one command should be defined.")
formatter_class = argparse.HelpFormatter
if 'formatter_class' in kwargs:
formatter_class = kwargs['formatter_class']
parser = ArgumentParser(**kwargs)
for name, value in _def.common_cmd_args.items():
parser.add_argument(*value.args, **value.kwargs)
if num_groups == 1:
"""register arguments as common"""
group = _def.groups[0]
for name, value in _def.grouped_cmd_args[group].items():
parser.add_argument(*value.args, **value.kwargs)
else:
"""register arguments as groups"""
subparsers = parser.add_subparsers(
title='commands', help='available commands', dest='command')
subparsers.required = True
for group in _def.groups:
subparser = subparsers.add_parser(
group, **_def.group_descriptions[group],
formatter_class=formatter_class)
for name, value in _def.grouped_cmd_args[group].items():
subparser.add_argument(*value.args, **value.kwargs)
return parser
def _split_lines(self, text, width):
text = re.sub(man_format_remove, '', text)
# this is the RawTextHelpFormatter._split_lines
if text.startswith('R|'):
return text[2:].splitlines()
return argparse.HelpFormatter._split_lines(self, text, width)
def parser_options(formatter_class=argparse.HelpFormatter):
"""
Retrieve a customized parser to generate man page
"""
return CommandlineParser().get_formatted_parser(formatter_class)
def _split_lines(self, text, width):
"""
Allows forcing newlines in lines starting with R|
"""
if text.startswith('R|'):
return text[2:].splitlines()
return argparse.HelpFormatter._split_lines(self, text, width)