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?
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!-)
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
epilog), orHelpFormatter (the formatter_class constructor argument) to customize how these strings are transformed into help text
argparse module bundles 3 alternative classes.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With