In argparse, is it possible to use -h option for anything other than 'help'?

Viewed 943

I am writing a code where I have to pass a hostname as an optional argument. It is also required to be passed with -h option.

Usage:

./program.py -h hostname

Argparse by default use -h for printing help. Is it possible to override that somehow?

1 Answers

No problem, all you have to do is pass add_help=False to the ArgumentParser constructor.

import argparse
parser = argparse.ArgumentParser(add_help=False)

If you still want to have the help functionality, however, it's not so easy. In that case, I would recommend just calling your host argument -H or something else. If you really want to do it, this is one method, but it's definitely a hack:

import argparse
parser = argparse.ArgumentParser(add_help=False)
parser._add_action(argparse._HelpAction(
    option_strings=['-H', '--help'],
    help='Show this help message and exit'
))

EDIT: thanks to @chepner for pointing out a cleaner way to add the help functionality:

parser.add_argument('-H', '--help', action='help',
    help='show this help message and exit')
Related