Created
April 30, 2016 19:50
-
-
Save carlopires/42fd290ba1391adb9a5c3bcf1a0e8b71 to your computer and use it in GitHub Desktop.
Python argparse boilerplate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
@author: Carlo Pires <[email protected]> | |
""" | |
import argparse | |
class Commands(object): | |
def status(self, args): | |
print('status for {}'.format(args.module)) | |
def reset(self, args): | |
print('reset for {}'.format(args.module)) | |
def disable(self, args): | |
print('disable for {}'.format(args.module)) | |
def enable(self, args): | |
print('enable for {}'.format(args.module)) | |
def reload(self, args): | |
print('reload for {}'.format(args.module)) | |
if __name__ == '__main__': | |
cmd = Commands() | |
mod_name_optional = argparse.ArgumentParser(add_help=False) | |
mod_name_optional.add_argument('--module', default='all', | |
metavar='<module name>') | |
mod_name_required = argparse.ArgumentParser(add_help=False) | |
mod_name_required.add_argument('module', metavar='<module name>') | |
def opt(parser, op_name, op_help, mod_opt): | |
op = parser.add_parser(op_name, parents=[mod_opt], help=op_help) | |
op.set_defaults(func=getattr(cmd, op_name)) | |
parser = argparse.ArgumentParser() | |
sp = parser.add_subparsers() | |
opt(sp, 'status', 'show the states of modules', mod_name_optional) | |
opt(sp, 'reset', 'reset the state for a module', mod_name_required) | |
opt(sp, 'enable', 'enable a module', mod_name_required) | |
opt(sp, 'disable', 'disable a module', mod_name_required) | |
opt(sp, 'reload', 'reload a modified module', mod_name_required) | |
args = parser.parse_args() | |
args.func(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment