1

I'm using Python's argparse module to create a CLI for my application. I've made a subparsers variable to store the parsers for each command, but when I can't find a way to change the title of the subparsers without modifying parser's (the main ArgumentParser's) internal variables.

Original Code

parser = ArgumentParser(prog="pacstall", formatter_class=CustomHelpFormatter)
subparsers = parser.add_subparsers(dest="command")

parser._subparsers.title = "commands"  # type: ignore[union-attr]
parser._optionals.title = "options"

Result

original_code_result

Edited Code

parser = ArgumentParser(prog="pacstall", formatter_class=CustomHelpFormatter)
subparsers = parser.add_subparsers(title="commands", dest="command")
parser._optionals.title = "options"

Result

edited_code_result

As you can see the order of the options and commands are switched if I make that change. Also I have no idea how to modify the title of the _optionals to "options" without modifying parser._optionals.title.

Here is my full parser file.

Wizard28
  • 355
  • 1
  • 3
  • 12

1 Answers1

0

The parser gets 2 initial argument_groups, with titles 'positional arguments' and 'optional arguments'. There's has been discussion about changing those, or giving users more control. But as you found, you can change them directly.

I won't tell anyone if you modify parser._options :)

You can also create your own argument_group - that's documented. You'll still get the default --help in the original (unless you disable that).

subparsers puts that argument in the 'positionals' by default. If you specify a 'title', it makes a new group.

Groups are displayed in the order that they were created, or rather the order that they appear in the parser._action_groups list. Look at parser.format_help to see how that's done.

hpaulj
  • 221,503
  • 14
  • 230
  • 353