Skip to content

Instantly share code, notes, and snippets.

@mxrch
Created December 2, 2021 01:37
Show Gist options
  • Save mxrch/cd0552ce6b41745a4868a50f39703937 to your computer and use it in GitHub Desktop.
Save mxrch/cd0552ce6b41745a4868a50f39703937 to your computer and use it in GitHub Desktop.
[Python Argparse] Add groups to multi subparsers
# Explication => https://stackoverflow.com/a/70193244/12778808
import argparse
import ctypes
parent_parser = argparse.ArgumentParser(description="Redacted")
subparsers = parent_parser.add_subparsers()
subparser_email = subparsers.add_parser("email", parents=[parent_parser], add_help=False)
subparser_gen = subparsers.add_parser("gen", parents=[parent_parser], add_help=False)
group_emails = subparser_email.add_argument_group("Main inputs")
group_gen = subparser_gen.add_argument_group("Emails generation")
group_matchers = parent_parser.add_argument_group("Matchers") # The group we want on each subparser
[...] # add the arguments to your groups here
def add_group_to_subparsers(group: argparse._ArgumentGroup, subparsers: argparse._SubParsersAction, name: str):
for name, subparser in subparsers._name_parser_map.items():
dummy_group = subparser.add_argument_group(name)
ctypes.memmove(id(dummy_group), id(group), object.__sizeof__(dummy_group))
add_group_to_subparsers(group_matchers, subparsers, "Matchers")
parent_parser.parse_args()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment