h4kr
h4kr

Reputation: 248

Writing commands and flags separate with argparse

I was writing down a code in python which makes use of argparse module to make it easier to use it.

I can add arguments in the form of flags like:

parser.add_argument('-u', '--url', dest='url', help='type in url')

But like in gobuster, when you use help flag (-h) you can see you can also pass commands like dir,fuzz,etc. They also have separate help flags for each of them like

gobuster dir --help

how to achieve this? I can make flags without arguments by:

parser.add_argument('R', action='store_true', help='allow recursion')

In short, I'm trying to find out how to define commands separately so that they also show up under commands in help section and not under optional arguments. I'm also trying to find out how to create a separate help section for each command.

Upvotes: 2

Views: 266

Answers (1)

Aadhavan Rajasekar
Aadhavan Rajasekar

Reputation: 21

It is possible to add it via subparsers with separate help message and parent arguments.

 arg_parser.add_argument('--version', action='version', version='%(prog)s 1.0')
 subparsers = arg_parser.add_subparsers(title='subcommands',dest='subcommandsarg',help='Program parser for subcommands')
 parser1 = argparse.ArgumentParser(add_help=False)
 parser1.add_argument('-a','--arg1', dest='module',required=False,help='Mod Name' ,default='all')
 subparsers.add_parser('parser1',parents=[parser1],help="Help text for parser1")
 parser2 = argparse.ArgumentParser(add_help=False)
 parser2.add_argument('-b','--arg2', dest='module',required=False,help='Mod Name' ,default='all')
 subparsers.add_parser('parser2',parents=[parser2],help="Gets the configuration of mods")
 options = arg_parser.parse_args()

output

#python test.py -h
usage: program [-h] [--version] {parser1,parser2} ...

optional arguments:
  -h, --help         show this help message and exit
  --version          show program's version number and exit

subcommands:
  {parser1,parser2}  Program parser for subcommands
    parser1          Help text for parser1
    parser2          Gets the configuration of mods

#python test.py parser1 -h
usage: program parser1 [-h] [-a MODULE]

optional arguments:
  -h, --help            show this help message and exit
  -a MODULE, --arg1 MODULE
                        Mod Name

#python test.py parser2 -h
usage: program parser2 [-h] [-b MODULE]

optional arguments:
  -h, --help            show this help message and exit
  -b MODULE, --arg2 MODULE
                        Mod Name

Upvotes: 1

Related Questions