Search code examples
pythonpython-2.7argparse

Python: how to add '-help' to argparse help command list?


Is there a way to include '-help' command to argparse help list?

I wish to have something like this on output, if i am typing '-help'.

optional arguments:
-h, -help, --help            show this help message and exit

Thanks


Solution

  • As @Akaisteph7 suggested:

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument('-help', action="help", help="second help :)")
    parser.add_argument('-f', '--foo')
    
    parser.print_help()
    
    0945:~/mypy$ python3 stack57058526.py 
    usage: stack57058526.py [-h] [-help] [-f FOO]
    
    optional arguments:
      -h, --help         show this help message and exit
      -help              second help :)
      -f FOO, --foo FOO
    

    Changing to:

    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument('-h','--help','-help', action="help", help="replacement help")
    
    0946:~/mypy$ python3 stack57058526.py 
    usage: stack57058526.py [-h] [-f FOO]
    
    optional arguments:
      -h, --help, -help  replacement help
      -f FOO, --foo FOO
    

    Adding the '-help' flag to the default help requires modifying a couple of 'private' attributes:

    parser = argparse.ArgumentParser()
    parser._actions[0].option_strings += ['-help']                                                          
    parser._option_string_actions['-help'] = parser._option_string_actions['-h']  
    
    0947:~/mypy$ python3 stack57058526.py 
    usage: stack57058526.py [-h] [-f FOO]
    
    optional arguments:
      -h, --help, -help  show this help message and exit
      -f FOO, --foo FOO
    

    If you want to build this change into your local version of argparse, you could modify this block of code in the ArgumentParser.__init__ method:

        if self.add_help:
            self.add_argument(
                default_prefix+'h', default_prefix*2+'help',
                action='help', default=SUPPRESS,
                help=_('show this help message and exit'))
    

    Whether you change a local copy of argparse.py, or subclass ArgumentParser is up to you.