【问题标题】:argparse custom action OOPargparse 自定义操作 OOP
【发布时间】:2021-11-07 12:14:47
【问题描述】:

我是 python 中 argparse 和 oop 的新手,我想在 argparse 中使用自定义操作,我已阅读 docs。基本上我只想在使用参数时运行一个函数,我不知道我到底应该做什么,创建另一个类并执行 __call__ 并将我的函数代码放在那里?因为那也不起作用。

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

现在你可以看到我想要做的很简单,我已经尝试了 2 天来找到解决方案,但我做不到。

【问题讨论】:

  • 请将其缩减为minimal reproducible example。我认为只需要一个论据来证明你的问题。请更详细地解释您要达到的目标以及这究竟是如何没有按预期工作的。
  • @mkrieger1 抱歉,我认为我删除了它们

标签: python oop argparse


【解决方案1】:

解析最好由单独的函数完成,当用作脚本时可以调用该函数。它不应该由import 执行。从命令行或其他来源获取用户输入应该与操作(类定义和使用)分开。

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

如果ItemData 是某种数据库提取器或打开器,您可能希望将其与search 分开。

虽然 Python 始终使用对象(argparse 是定义类的一个很好的模块示例),但作为用户,您不必创建类来完成工作。这可能是组织任务的一种方便方式,但 Python 并没有正式要求它(与 Java 之类的东西相反)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多