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?

3
  • Does this answer your question? Using the same option multiple times in Python's argparse Commented Nov 17, 2020 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? Commented Nov 17, 2020 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. Commented Nov 17, 2020 at 18:05

1 Answer 1

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) 
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.