cpython: 97b28115bd08 (original) (raw)

--- a/Doc/library/argparse.rst +++ b/Doc/library/argparse.rst @@ -1668,6 +1668,18 @@ Sub-commands >>> parser.parse_args(['co', 'bar']) Namespace(foo='bar')

+ One particularly effective way of handling sub-commands is to combine the use of the :meth:add_subparsers method with calls to :meth:set_defaults so that each subparser knows which Python function it should execute. For

--- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -1110,6 +1110,12 @@ class _SubParsersAction(Action): parser_name = values[0] arg_strings = values[1:]

+ # set the parser name if requested if self.dest is not SUPPRESS: setattr(namespace, self.dest, parser_name) @@ -2307,11 +2313,18 @@ class ArgumentParser(_AttributeHolder, _ def _check_value(self, action, value): # converted value must be one of the choices (if specified)

# ======================= # Help-formatting methods

--- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -1842,6 +1842,22 @@ class TestAddSubparsers(TestCase): parser3.add_argument('t', type=int, help='t help') parser3.add_argument('u', nargs='...', help='u help')

+

+ # return the main parser return parser @@ -1857,6 +1873,24 @@ class TestAddSubparsers(TestCase): args = args_str.split() self.assertArgumentParserError(self.parser.parse_args, args)

+ def test_parse_args(self): # check some non-failure cases: self.assertEqual( @@ -1909,78 +1943,80 @@ class TestAddSubparsers(TestCase): def test_help(self): self.assertEqual(self.parser.format_usage(),

main description positional arguments:

optional arguments:

def test_help_extra_prefix_chars(self): # Make sure - is still used for help if it is a non-first prefix char parser = self._get_parser(prefix_chars='+:-') self.assertEqual(parser.format_usage(),

main description positional arguments:

optional arguments:

def test_help_alternate_prefix_chars(self): parser = self._get_parser(prefix_chars='+:/') self.assertEqual(parser.format_usage(),

main description positional arguments:

optional arguments:

def test_parser_command_help(self): self.assertEqual(self.command_help_parser.format_usage(),

main description positional arguments:

optional arguments:

def test_subparser_title_help(self): @@ -2083,6 +2119,8 @@ class TestAddSubparsers(TestCase): 1 help 2 2 help 3 3 help

============