fromargparseimportActionfromargparseimportArgumentErrorfromargparseimportArgumentParserasBaseArgumentParserfromargparseimportHelpFormatterasBaseHelpFormatterfromcollectionsimportdefaultdict__version__="0.1.0"classPrintAction(Action):def__call__(self,parser,namespace,values,option_string=None):parser.exit(message="Another print and then exit message like help action\n")classParseKVAction(Action):def__call__(self,parser,namespace,values,option_string=None):setattr(namespace,self.dest,defaultdict(str))foreachinvalues:try:key,value=each.split("=")getattr(namespace,self.dest)[key]=valueexceptValueErrorasex:message="\nTraceback: {}".format(ex)message+="\nError on '{}' || It should be 'key=value'".format(each)raiseArgumentError(self,str(message))classHelpFormatter(BaseHelpFormatter):def__init__(self,prog):super(HelpFormatter,self).__init__(prog=prog,max_help_position=32,width=100)classArgumentParser(BaseArgumentParser):def__init__(self):super(ArgumentParser,self).__init__(description="A sample argument parser",formatter_class=HelpFormatter,)sites=map(str,["x","y","z"])self.add_argument("--tag",type=str,help="Tag, choose from {%(choices)s}",choices=sites,metavar="VALUE",required=True,)self.add_argument("--version",action="version",help="Show program's version number and exit",version=__version__,)self.add_argument("--verbose",help="See more detailed logs",action="store_true",default=False,)self.add_argument("-p","--print",action=PrintAction,nargs=0,help="Show print message and exit",default=False,)self.add_argument("-H","--host-names",dest="hosts",nargs='+',action=ParseKVAction,help='Parameter accepts -H host1=localhost "host2=other hosts"',metavar="KEY1=VALUE1",)args=ArgumentParser().parse_args()print(args)
from__future__importprint_functionimportargparseimportsysimporttextwrapimportwarningsfromargparseimportHelpFormatterasBaseHelpFormatter__version__="0.1.0"warnings.filterwarnings("ignore")classAboutParser(argparse.ArgumentParser):title="about"description="Show information about it"defhandle(self,arguments):usage=textwrap.dedent("""\ What is it ? It is what it is! """)sys.stdout.write(usage)classWebParser(argparse.ArgumentParser):title="web"description="Webserver runner"def__init__(self,**kwargs):super().__init__(**kwargs)self.add_argument("--host",type=str,help="Webserver host(default: %(default)s)",metavar="VALUE",default="0.0.0.0")self.add_argument("--port",help="Webserver port (default: %(default)s)",type=int,default=5000,metavar="VALUE",)defhandle(self,arguments):print(arguments)classCLIParser(argparse.ArgumentParser):title="cli"description="CLI runner"def__init__(self,**kwargs):# lazy importsuper().__init__(**kwargs)self.add_argument("--site",type=str,help="Old site, choose from {%(choices)s}",choices=["localhost","yarimdunya"],metavar="VALUE",required=True,)self.add_argument("-y","--yes",dest="yes",help="Disable interactivity",action="store_true",default=False,)defhandle(self,arguments):print(arguments)classHelpFormatter(BaseHelpFormatter):def__init__(self,prog):super().__init__(prog=prog,max_help_position=32,width=100)classMainParser(argparse.ArgumentParser):def__init__(self,commands:list):super().__init__()self.available_commands=commandsself.add_argument("command",choices=self._get_available_commands(),help="subcommands")self.add_argument("-v","--version",action="version",help="show program's version number and exit",version=__version__,)def_get_available_commands(self):return{cmd.titleforcmdinself.available_commands}defparse_args(self,*_):args=super().parse_args(sys.argv[1:2])self.parse(args.command)returnargsdefparse(self,cmd):foreachinself.available_commands:ifeach.title==cmd:parser_class=eachbreakelse:raiseValueError("No such commands: {}".format(cmd))parser=parser_class(prog="{}{}".format(self.prog,cmd),description=parser_class.description,formatter_class=HelpFormatter,)self._register_global_arguments(parser)arguments=parser.parse_args(sys.argv[2:])parser.handle(arguments)@staticmethoddef_register_global_arguments(parser):parser.add_argument("-V","--verbose",dest="verbose",help="set logger to debug to see more detailed logs",action="store_true",default=False,)defformat_usage(self):returnself.format_help()defformat_help(self):commands=""foreachinself.available_commands:commands+=" {}{}\n".format(each.title.ljust(24),each.description)help_msg=textwrap.dedent("""\ Main Parser {version} USAGE {prog} [-h] [-v] <command> [<arg1>] ... [<argN>] ARGUMENTS <command> The command to execute <arg> The arguments of the command GLOBAL OPTIONS -h (--help) Display this help message -v (--version) Display this application version AVAILABLE COMMANDS {commands} """).format(version=__version__,prog=self.prog,commands=commands,)returnhelp_msgdefmain():commands=[AboutParser,CLIParser,WebParser]parser=MainParser(commands=commands)parser.parse_args()if__name__=='__main__':main()