Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 979
hax Avatar asked Oct 23 '25 14:10

hax


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')
like image 157
C. Feenstra Avatar answered Oct 26 '25 03:10

C. Feenstra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!