简体   繁体   中英

argparse custom action OOP

i'm new to argparse and oop in python, i want to use a custom action in argparse, i have read the docs . basically i just want to run a function if an argument is used, i don't know what the hell i'm supposed to do, create another class and do a __call__ and put my function code in there? cause that doesn't work either.

class UserSearch:
    def __init__(self) -> None:
        self.args = self.get_args()
        self.data = ItemData(domains[self.args.type], self.args.name).output()

    def get_args(self):
        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)   
        parser.add_argument(
            "-c",
            "--color",
            help="Color of the item you want to search for.",
            default="",
            nargs="*",
            action=self.getcolors(),
        )

        return parser.parse_args()

    def getcolors(self):
        args = self.args
        data = self.data
        user_selection = []
        for k in args.color:
            sregex = re.compile(fr".*{k}.*", re.I | re.U)
            for i in range(len(data)):
                for j in list(data[i]["color"].keys()):
                    # print(data[i])
                    try:
                        if sregex.match(j).group(0):
                            user_selection.append(data[i])
                    except AttributeError:
                        continue
        return user_selection

now as u can see what i want to do is pretty simple, i've tried for 2 days to find solution and i just can't.

Parsing is best done by a separate function, that can be called when used as a script. It should not be performed by an import . Getting user input, from command line or other source should be separate from the action (class definition and use).

def get_args(argv=None):
        parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)   
        parser.add_argument(
            "-c",
            "--color",
            help="Color of the item you want to search for.",
            default="",
            nargs="*",
            action=self.getcolors(argv),
        )

        return parser.parse_args()

class UserSearch:
    def __init__(self, args) -> None:
        self.args = args
        self.data = ItemData(domains[self.args.type], self.args.name).output()
    # your parser doesn't specify a 'type`' argument
    # not 'name' either


    def getcolors(self):
        args = self.args
        data = self.data
        user_selection = []
        for k in args.color:
            sregex = re.compile(fr".*{k}.*", re.I | re.U)
            for i in range(len(data)):
                for j in list(data[i]["color"].keys()):
                    # print(data[i])
                    try:
                        if sregex.match(j).group(0):
                            user_selection.append(data[i])
                    except AttributeError:
                        continue
        return user_selection

if __name__ == '__main__':
    args = get_args()
    user = UserSearch(args)
    # use user

If ItemData is some sort of database fetcher or opener, you might want to separate that from the search .

While Python uses objects throughout (and argparse is a good example of module that defines classes), you, as the user, don't have to create a class to do your job. It may be a convenient way of organizing the task, but Python does not formally require it (in contrast to something like Java ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM