From 484f6116cbeb2db20e15615af5f6b2d6d0010a05 Mon Sep 17 00:00:00 2001 From: Patricio Paez Date: Wed, 23 Nov 2022 15:03:41 -0600 Subject: [PATCH 1/3] Show the main help if no arguments and using sub-commands --- Doc/library/argparse.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/Doc/library/argparse.rst b/Doc/library/argparse.rst index c55d94421e5b14..297f4636d81ece 100644 --- a/Doc/library/argparse.rst +++ b/Doc/library/argparse.rst @@ -1866,6 +1866,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 From 268de9035b60382e1aa132c7045476214b9bf5ee Mon Sep 17 00:00:00 2001 From: Patricio Paez Date: Wed, 23 Nov 2022 15:06:15 -0600 Subject: [PATCH 2/3] Add this case to the example --- Doc/library/argparse.rst | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Doc/library/argparse.rst b/Doc/library/argparse.rst index 297f4636d81ece..765eaf37da68ad 100644 --- a/Doc/library/argparse.rst +++ b/Doc/library/argparse.rst @@ -1889,6 +1889,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 From a2687c655572e154d7e42ac7ad5e6602f4e3feb5 Mon Sep 17 00:00:00 2001 From: Patricio Paez Date: Wed, 23 Nov 2022 15:08:01 -0600 Subject: [PATCH 3/3] Add explanation in the documentation --- Doc/library/argparse.rst | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/Doc/library/argparse.rst b/Doc/library/argparse.rst index 765eaf37da68ad..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):