Overriding argparse -h behaviour part 2

Question:

I am using python’s argparse and would like to use the -h flag for my own purposes. Here’s the catch — I still want to have –help be available, so it seems that parser = argparse.ArgumentParser('Whatever', add_help=False) is not quite the solution.

Is there an easy way to re-use the -h flag while still keeping the default functionality of –help?

Asked By: user3481267

||

Answers:

Initialize ArgumentParser with add_help=False, add --help argument with action="help":

import argparse

parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('--help', action="help")
parser.add_argument('-h', help='My argument')

args = parser.parse_args()
...

Here’s what on the command-line:

$ python test_argparse.py --help
usage: test_argparse.py [--help] [-h H]

optional arguments:
  --help
  -h H    My argument

Hope this is what you need.

Answered By: alecxe

Another way to do this, with less code, is to put in the ArgumentParser initialization conflict_handler='resolve'. This also leaves the message show this help message and exit on the --help output.

So the code:

import argparse

parser = argparse.ArgumentParser(conflict_handler='resolve')
parser.add_argument('-h', help='My argument')

args = parser.parse_args()

Produces this output:

$ python args.py --help
usage: args.py [--help] [-h H]

options:
  --help  show this help message and exit
  -h H    My argument
Answered By: Mordechai
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.