【发布时间】: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 抱歉,我认为我删除了它们