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

时间:2019-06-05 09:24:56

标签: python python-2.7 argparse

就像标题中所说的,我有一个解析器,它必须对一个参数做2件事,

  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,如果是,则将函数副本添加到列表任务中。但这似乎是一种解决方法,所以我希望有一种更好的方法,而无需对参数进行后处理。

1 个答案:

答案 0 :(得分:1)

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

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

我也许可以使自定义函数更通用,但这足以解决这种情况。

相关问题