Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding selected subcommands using argparse

I am using argparse and have set-up subcommands to my program. I have created sub-parsers to define these sub-commands. I have some admin commands that shouldn't be shown to users in the help screen. I know we could hide arguments of a sub-command, but I don't know how we could hide few of the subcommands from showing up in the help list.

Here's my code snippet,

parser = argparse.ArgumentParser(prog='myProg',
                                    description=desc,
                                   formatter_class=argparse.RawDescriptionHelpFormatter)

subparsers = parser.add_subparsers(dest='sub_parser_name')


myProg_query.add_subparser(subparsers)
myProg_update.add_subparser(subparsers)
myProg_configure.add_subparser(subparsers)
myProg_result.add_subparser(subparsers)

When I run the help command, I get this

%> myProg --help
usage: myProg [-h] 

positional arguments:
{query,update,configure,result}
query               query information
update              Update 
configure           Configure system
result              tabulate the result

From the help output, I would want to display only "query" and "result" to the user. I tried to use argparse.SUPPRESS in add_subparser method, but it would hide all the subcommands. Whatever I searched only talked about hiding individual arguments of each sub-command, but not about hiding sub-command. I might have to create a custom formatter method, but wanted to check if there were any other way to achieve this.

like image 651
abs Avatar asked Feb 11 '14 03:02

abs


1 Answers

looks like I found a solution for this issue without any patches for argparse. It's enough to modify 'metavar' and do not set 'help' for the certain subparser.

import argparse

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(title='commands', metavar='{command}')

command = subparsers.add_parser("command",
                                help='command help.',
                                description='command description.')
suppress_command = subparsers.add_parser("suppress_command",
                                         help=argparse.SUPPRESS,
                                         description='suppress command.')
hidden_command = subparsers.add_parser("hidden_command",
                                       description='Hidden command.')

This results in

[root@localhost ~]# parser -h
usage: parser [-h] {command} ...

optional arguments:
-h, --help        print help message and exit

commands:
{command}
    command           command help.
    suppress_command  ==SUPPRESS==

[root@localhost ~]# parser hidden_command -h
usage: parser hidden_command [-h]

Hidden command.

optional arguments:
-h, --help  show this help message and exit
like image 160
Froth Avatar answered Sep 22 '22 11:09

Froth