Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top