Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append extra text to "--help" in argparse

When you run

foo.py -h

OR

foo.py --help,

you will get a "help" message about how to use foo.py and what arguments that it takes. Is there a way I can append to this message? Printing __doc__ for example?

like image 996
Omar Avatar asked Jul 05 '26 03:07

Omar


2 Answers

Sure, argparse gives you a lot of customization possibilities. To "append" to the help (print more after the help message is done), for example, use the epilog named argument.

parser = argparse.ArgumentParser(epilog="That's all she wrote", ...)

where ... stands for "whatever other named arguments you want to pass to the parser constructor", the message in question will be printed on --help after the help about arguments.

See https://docs.python.org/3/library/argparse.html for a few thousand words about argparse (written as a reference but with lots of examples) and https://docs.python.org/3/howto/argparse.html#id1 for a few thousand more (written as a tutorial). Maybe half those docs are about how to fine-tune messages for --help or error cases!-)

like image 167
Alex Martelli Avatar answered Jul 06 '26 16:07

Alex Martelli


The help-formatting function, argparse.ArgumentParser.format_help(), looks like this:

def format_help(self):
        formatter = self._get_formatter() #by default, an instance of argparse.HelpFormatter

        # usage
        formatter.add_usage(self.usage, self._actions,
                            self._mutually_exclusive_groups)

        # description
        formatter.add_text(self.description)

        # positionals, optionals and user-defined groups
        for action_group in self._action_groups:
            formatter.start_section(action_group.title)
            formatter.add_text(action_group.description)
            formatter.add_arguments(action_group._group_actions)
            formatter.end_section()

        # epilog
        formatter.add_text(self.epilog)

        # determine help from format above
        return formatter.format_help()

So, you can either

  • customize the strings used (they can be passed as constructor arguments, you're probably interested in epilog), or
  • replace the default HelpFormatter (the formatter_class constructor argument) to customize how these strings are transformed into help text
    • the argparse module bundles 3 alternative classes.
like image 40
ivan_pozdeev Avatar answered Jul 06 '26 18:07

ivan_pozdeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!