24

I have a certain config file which calls upon its plugins. It's possible to pass arguments to those plugins. This config file also lets me call arbitary commands at runtime.

The plugins use many arguments: one of them is -h and it does not stand for --help. Now, my issue is that I want to call my own Python script as well as pass it some arguments. I'm using argparse and wanting to be consistent with the rest of the config, I created a -h flag. To my surprise, argparse just gives me argparse.ArgumentError: argument -h/--help: conflicting option string(s): -h instead of minding its own business.

Is there a way to stop this from happening?

I am well aware that most people expect -h to give help but it's my own script and I think I know better what I want to use a flag for than the argparse devs.

Mateusz Kowalczyk
  • 2,036
  • 1
  • 15
  • 29
  • You do indeed know better than the argparse devs, which is precisely why you have to say what you mean and not just trust them to guess your mind correctly. Default `-h --help` makes sense because it is so common. Telling you when you've accidentally introduced a clash with the common default expectation is a good thing. All you need to do is tell argparse that you intended to do that and all is well! – Ben Feb 19 '13 at 06:28

3 Answers3

35

Look in the argparse documentation for the ArgumentParser arguments. There's one called add_help, which defaults to True.

parser = argparse.ArgumentParser('Cool', add_help=False)
parser.add_argument('-h', '--hi', action='store_true', dest='hi')

This works as expected.

deadfoxygrandpa
  • 617
  • 4
  • 9
14

If you give the ArgumentParser a conflict_handler="resolve" argument, adding your own -h will override the existing one, while keeping --help functional.

#!/usr/bin/env python3
import argparse
parse = argparse.ArgumentParser(conflict_handler="resolve")
parse.add_argument("-h", "--hello")
print(parse.parse_args())
Alcaro
  • 1,664
  • 16
  • 21
  • This one is the correct answer, or rather, the one that is useful in the most use cases. – MSmedberg Oct 23 '20 at 15:13
  • @MSmedberg, There are some cases where we prefer no to use the `"resolve"` in the `ArgumentParser` so this solution doesn't fit for all cases – Yoni Melki Jun 26 '21 at 08:13
10

There is a kwarg to suppress that stuff (docs).
Create your parser like this:

parser = argparse.ArgumentParser(prog='PROG', add_help=False)
wim
  • 338,267
  • 99
  • 616
  • 750