.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \
[parser_class], [action], \
- [option_string], [dest], [help], \
- [metavar])
+ [option_string], [dest], [required] \
+ [help], [metavar])
Many programs split up their functionality into a number of sub-commands,
for example, the ``svn`` program can invoke sub-commands like ``svn
* dest_ - name of the attribute under which sub-command name will be
stored; by default ``None`` and no value is stored
+ * required_ - Whether or not a subcommand must be provided, by default
+ ``True``.
+
* help_ - help for sub-parser group in help output, by default ``None``
* metavar_ - string presenting available sub-commands in help; by default it
'bar', type=float, help='bar help')
# check that only one subparsers argument can be added
- subparsers_kwargs = {}
+ subparsers_kwargs = {'required': False}
if aliases:
subparsers_kwargs['metavar'] = 'COMMAND'
subparsers_kwargs['title'] = 'commands'
self.assertEqual(NS(foo=False, bar='1', baz='2'),
parser.parse_args('1 2'.split()))
+ def _test_required_subparsers(self, parser):
+ # Should parse the sub command
+ ret = parser.parse_args(['run'])
+ self.assertEqual(ret.command, 'run')
+
+ # Error when the command is missing
+ self.assertArgumentParserError(parser.parse_args, ())
+
+ def test_required_subparsers_via_attribute(self):
+ parser = ErrorRaisingArgumentParser()
+ subparsers = parser.add_subparsers(dest='command')
+ subparsers.required = True
+ subparsers.add_parser('run')
+ self._test_required_subparsers(parser)
+
+ def test_required_subparsers_via_kwarg(self):
+ parser = ErrorRaisingArgumentParser()
+ subparsers = parser.add_subparsers(dest='command', required=True)
+ subparsers.add_parser('run')
+ self._test_required_subparsers(parser)
+
+ def test_required_subparsers_default(self):
+ parser = ErrorRaisingArgumentParser()
+ subparsers = parser.add_subparsers(dest='command')
+ subparsers.add_parser('run')
+ self._test_required_subparsers(parser)
+
+ def test_optional_subparsers(self):
+ parser = ErrorRaisingArgumentParser()
+ subparsers = parser.add_subparsers(dest='command', required=False)
+ subparsers.add_parser('run')
+ # No error here
+ ret = parser.parse_args(())
+ self.assertIsNone(ret.command)
+
def test_help(self):
self.assertEqual(self.parser.format_usage(),
'usage: PROG [-h] [--foo] bar {1,2,3} ...\n')