diff --git a/Doc/library/argparse.rst b/Doc/library/argparse.rst index c55d94421e5b14..042ec1174001f6 100644 --- a/Doc/library/argparse.rst +++ b/Doc/library/argparse.rst @@ -1852,10 +1852,13 @@ 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 - example:: + 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. The :meth:`set_defaults` method of the + main parser is called to handle the case when no subcommand is + included in the command line. The main parser :meth:`print_help` + method is called to display the help in this case. For example:: >>> # sub-command functions >>> def foo(args): @@ -1866,6 +1869,7 @@ Sub-commands ... >>> # create the top-level parser >>> parser = argparse.ArgumentParser() + >>> parser.set_defaults(func=lambda args: parser.print_help()) >>> subparsers = parser.add_subparsers() >>> >>> # create the parser for the "foo" command @@ -1888,6 +1892,17 @@ Sub-commands >>> args = parser.parse_args('bar XYZYX'.split()) >>> args.func(args) ((XYZYX)) + >>> + >>> # show the help when called without arguments + >>> args = parser.parse_args() + >>> args.func(args) + usage: app.py [-h] {foo,bar} ... + + positional arguments: + {foo,bar} + + options: + -h, --help show this help message and exit This way, you can let :meth:`parse_args` do the job of calling the appropriate function after argument parsing is complete. Associating