Skip to main content
 首页 » 编程设计

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

2024年11月24日9zhoujg

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

  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') 

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