Search code examples
pythonargparse

Overriding argparse -h behaviour part 2


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?


Solution

  • 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.