0

Inside my project I'm mostly using docopt, but to overcome a limitation I'm switching to argparse for one function. However, for consistency I want to still print my own doc-string when I type -h or --help. Surprisingly I cannot find how to do that.

This doesn't work:

parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS, help=__doc__)

as it gives

argparse.ArgumentError: argument -h/--help: conflicting option strings: -h, --help

But what do I have to put?

Tom de Geus
  • 5,625
  • 2
  • 33
  • 77
  • Does this answer your question? [Using the same option multiple times in Python's argparse](https://stackoverflow.com/questions/36166225/using-the-same-option-multiple-times-in-pythons-argparse) – Serial Lazer Nov 17 '20 at 10:48
  • @SerialLazer Thanks. I'm not sure... Or rather I don't think so. What I want to do it simply to pring something else when `argparse` would print the docstring, I don't want to add an option on top of it. But maybe I'm overlooking something? – Tom de Geus Nov 17 '20 at 10:51
  • `--help` is included by default; so that's why adding your own produces a conflict. There is a `ArgumentParser` parameter to turns off the automatic help argument. Specifying the `help=__doc__` doesn't help since the just changes the help line in the conventional help display. It doesn't change the whole display. – hpaulj Nov 17 '20 at 18:05

1 Answers1

1

I found that one solution is to overwrite the default print_help function, as follows:

import argparse

class Parser(argparse.ArgumentParser):

    def print_help(self):
        print(__doc__)

parser = Parser()
parser.add_argument('-f', '--foo', required=False)
Tom de Geus
  • 5,625
  • 2
  • 33
  • 77
  • I think this the best. `ipython` accomplishes something similar by looking at `sys.argv` before using the `argparse` parser. In other words, it captures the `help` command first. – hpaulj Nov 17 '20 at 18:06