gpt4 book ai didi

python - 是否可以对 argparse 参数执行 2 个操作?

转载 作者:太空宇宙 更新时间:2023-11-04 04:10:04 25 4
gpt4 key购买 nike

如标题所说,我有一个解析器必须对一个参数做两件事,

  1. 它必须将一个 const 附加到一个列表(一个列表,该列表为程序提供了它必须处理的所有功能)
  2. 必须将此参数后的值添加到变量中,以便稍后使用

解析器的某些代码(将失败,因为定义 2 次 '-copy' 将不起作用:

parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter, description="""some help text""")
# ... more arguments, but not a problem
parser.add_argument('-ls','--list',action='append_const', dest='tasks',const=ls, help='outputs the filelocation if match was found')
parser.add_argument('-copy', action='append_const', dest='tasks',const=copy, help='copies the file to the given location if a match was found')
parser.add_argument('-copy', dest='copyLocation', help='outputs the filelocation if match was found')

有人知道如何解决这个问题并使 -copy 参数同时执行存储和 append_const 吗?

我知道我可以对 args 进行“后处理”并检查其中是否有 -copy,如果有,则将函数副本添加到任务列表中。但这接缝就像一种解决方法,所以我希望有一种更好的方法来做事而不用对参数进行后处理。

最佳答案

感谢对自定义操作的评论,我找到了添加它的好方法:)

#custom action for store and append_const
class StoreValueAndAppendConst(argparse.Action):
def __init__(self, option_strings, dest, nargs=None, **kwargs):
if nargs is not None:
raise ValueError("nargs not allowed")
if "task" in kwargs:
self.task = kwargs["task"]
del kwargs["task"]
super(StoreValueAndAppendConst, self).__init__(option_strings, dest, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
#add the task to the list of tasks.
if not namespace.tasks:
namespace.tasks = []
namespace.tasks.append(self.task)
setattr(namespace, self.dest, values) #do the normal store

实际调用变为:

parser.add_argument('-copy', action=StoreValueAndAppendConst, dest='copy', task=copy, help='outputs the filelocation if match was found')

我可以使自定义函数更通用,但这对于这种情况已经足够了。

关于python - 是否可以对 argparse 参数执行 2 个操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56457706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com