Created
April 24, 2018 20:31
-
-
Save kmkmjhyiiiu/8c8a2be40eb2048e3ced228a52af9b83 to your computer and use it in GitHub Desktop.
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
from argparse import ArgumentParser | |
import os | |
import sys | |
class ArgParser(object): | |
def __init__(self): | |
self.parser = ArgumentParser() | |
self.isPrinted = False | |
def add(self, name: str, optional: bool = True, **kwarg: dict) -> object: | |
if not 'const' in kwarg: | |
kwarg['const'] = 1 | |
if not 'nargs' in kwarg: | |
kwarg['nargs'] = "?" | |
if optional is False: | |
self.parser.add_argument(name, require=True, **kwarg) | |
else: | |
self.parser.add_argument(name, **kwarg) | |
return self | |
def parse(self) -> object: | |
return self.parser.parse_args() | |
def runFunc(self, name: dict, **requiredArgument: list, printHelp = False) -> str or tuple: | |
""" Run Function on give argument | |
name: dict | |
key -> argument name | |
value -> unbound function | |
requireArgument | |
keys -> argument name | |
values -> function argument | |
for example running abc on --abc --lol test | |
where lol must be passed but as parameter l | |
so | |
runFunc({'abc': func}, {'lol': 'l'}) | |
it gonna be something like this: | |
abc(l=lol) | |
where lol is argument value | |
""" | |
parse = self.parse() | |
argName = list(name.keys())[0] | |
func = list(name.values())[0] | |
attr = getattr(parse, argName) | |
if attr: | |
self.isPrinted = True | |
arguments = {} | |
for arg in requiredArgument: | |
value = getattr(parse, arg) | |
paramter = requiredArgument[arg] | |
if value or value is None: | |
arguments[paramter] = value | |
else: | |
print('Please Give Argument: "{}" is important for argument: "{}"'.format(arg, argName)) | |
os._exit(1) | |
func(**arguments) | |
if printHelp: | |
self.help() | |
def help(self): | |
if len(sys.argv) < 2 and self.isPrinted is False: | |
self.isPrinted = True | |
self.parser.print_help() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment