argparse: Associate arguments with another argument

允我心安 提交于 2019-12-07 18:19:44

问题


With argparse, it's possible to repeat an argument and collect all the values into a list:

parser = ArgumentParser()
parser.add_argument('-o', '--output', action='append')

args = parser.parse_args(['-o', 'output1', '-o', 'output2'])
print(vars(args))
# {'output': ['output1', 'output2']}

I'm looking for a way to associate flags with each of these arguments, so that it's possible to do this:

args = parser.parse_args(['-o', 'output1', '--format', 'text',
                          '-o', 'output2', '--format', 'csv'])

And get an output like this (or something similar):

{'output': {'output1': {'format': 'text'},
            'output2': {'format': 'csv'}
           }
}

Ideally, these flags should follow the usual semantics - for example, --format could be optional, or there could be multiple arguments associated with each -o output, in which case they should be passable in any order (i.e. -o output1 -a -b -c should be equivalent to -o output1 -c -a -b).

Can this be done with argparse?


回答1:


3 parsers operating on a general set of -o and -f flags:

Simple append - no connection between the 2 dest:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output', action='append')
parser.add_argument('-f', '--format', action='append')

args = parser.parse_args(['-o', 'output1', '-o', 'output2'])
print(args)
args = parser.parse_args(['-o', 'output1', '--format', 'text',
                          '-o', 'output2', '--format', 'csv'])
print(args)

args = parser.parse_args(['-o', 'output1',
                          '-o', 'output2', '--format', 'csv',
                          '-o', 'output3', '-f1', '-f2'])
print(args)
print()

nargs='+'; keeps arguments together, but does not use format flags:

parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output', action='append', nargs='+')
#parser.add_argument('-f', '--format', action='append')

args = parser.parse_args(['-o', 'output1', '-o', 'output2'])
print(args)
args = parser.parse_args(['-o', 'output1', 'text',
                          '-o', 'output2', 'csv'])
print(args)

args = parser.parse_args(['-o', 'output1',
                          '-o', 'output2', 'csv',
                          '-o', 'output3', '1', '2'])
print(args)
print()

Custom classes derived from the append class. Creates a dictionary for each output. format modifies the last output dictionary:

class Foo1(argparse._AppendAction):
    def __call__(self, parser, namespace, values, option_string=None):
        items = argparse._copy.copy(argparse._ensure_value(namespace, self.dest, []))
        dd = {'output': values, 'format': []}
        items.append(dd)
        setattr(namespace, self.dest, items)

class Foo2(argparse._AppendAction):
    def __call__(self, parser, namespace, values, option_string=None):
        items = argparse._copy.copy(argparse._ensure_value(namespace, self.dest, []))
        last = items[-1]   # error if -f before -o
        last['format'].append(values)
        setattr(namespace, self.dest, items)

parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output', action=Foo1)
parser.add_argument('-f', '--format', action=Foo2, dest='output')

args = parser.parse_args(['-o', 'output1', '-o', 'output2'])
print(args)
args = parser.parse_args(['-o', 'output1', '--format', 'text',
                          '-o', 'output2', '--format', 'csv'])
print(args)

args = parser.parse_args(['-o', 'output1',
                          '-o', 'output2', '--format', 'csv',
                          '-o', 'output3', '-f1', '-f2'])
print(args)
print()

produces:

1238:~/mypy$ python stack48504770.py 
Namespace(format=None, output=['output1', 'output2'])
Namespace(format=['text', 'csv'], output=['output1', 'output2'])
Namespace(format=['csv', '1', '2'], output=['output1', 'output2', 'output3'])

Namespace(output=[['output1'], ['output2']])
Namespace(output=[['output1', 'text'], ['output2', 'csv']])
Namespace(output=[['output1'], ['output2', 'csv'], ['output3', '1', '2']])

Namespace(output=[{'output': 'output1', 'format': []}, 
                  {'output': 'output2', 'format': []}])
Namespace(output=[{'output': 'output1', 'format': ['text']}, 
                  {'output': 'output2', 'format': ['csv']}])
Namespace(output=[{'output': 'output1', 'format': []}, 
                  {'output': 'output2', 'format': ['csv']}, 
                  {'output': 'output3', 'format': ['1', '2']}])
()



回答2:


Based on the code in hpaulj's answer, I've tweaked the implementation to make it more versatile. It consists of 2 custom Action classes, ParentAction and ChildAction.

Usage

parser = argparse.ArgumentParser()
# first, create a parent action:
parent = parser.add_argument('-o', '--output', action=ParentAction)
# child actions require a `parent` argument:
parser.add_argument('-f', '--format', action=ChildAction, parent=parent)
# child actions can be customized like all other Actions. For example,
# we can set a default value or customize its behavior - the `sub_action`
# parameter takes the place of the usual `action` parameter:
parser.add_argument('-l', '--list', action=ChildAction, parent=parent,
                    sub_action='append', default=[])

args = parser.parse_args(['-o', 'output1', '-l1', '-l2',
                          '-o', 'output2', '--format', 'csv',
                          '-o', 'output3', '-f1', '-f2'])
print(args)
# output (formatted):
# Namespace(
#     output=OrderedDict([('output1', Namespace(list=['1', '2'])),
#                         ('output2', Namespace(format='csv', list=[])),
#                         ('output3', Namespace(format='2', list=[]))
#                         ])
# )

Caveats

  • Child actions must always follow after parent actions. For example, --format csv -o output1 would not work and show an error message.
  • It's not possible to register multiple ChildActions with the same name, even with different parents.

    Example:

    parent1 = parser.add_argument('-o', '--output', action=ParentAction)
    parser.add_argument('-f', action=ChildAction, parent=parent1)
    parent2 = parser.add_argument('-i', '--input', action=ParentAction)
    parser.add_argument('-f', action=ChildAction, parent=parent2)
    
    # throws exception:
    # argparse.ArgumentError: argument -f: conflicting option string: -f
    

Code

import argparse

from collections import OrderedDict


class ParentAction(argparse.Action):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, default=OrderedDict(), **kwargs)

        self.children = []

    def __call__(self, parser, namespace, values, option_string=None):
        items = getattr(namespace, self.dest)
        nspace = type(namespace)()
        for child in self.children:
            if child.default is not None:
                setattr(nspace, child.name, child.default)
        items[values] = nspace

class ChildAction(argparse.Action):
    def __init__(self, *args, parent, sub_action='store', **kwargs):
        super().__init__(*args, **kwargs)

        self.dest, self.name = parent.dest, self.dest
        self.action = sub_action
        self._action = None
        self.parent = parent

        parent.children.append(self)

    def get_action(self, parser):
        if self._action is None:
            action_cls = parser._registry_get('action', self.action, self.action)
            self._action = action_cls(self.option_strings, self.name)
        return self._action

    def __call__(self, parser, namespace, values, option_string=None):
        items = getattr(namespace, self.dest)
        try:
            last_item = next(reversed(items.values()))
        except StopIteration:
            raise argparse.ArgumentError(self, "can't be used before {}".format(self.parent.option_strings[0]))
        action = self.get_action(parser)
        action(parser, last_item, values, option_string)



回答3:


Just define -o to take two arguments.

parser.add_argument('-o', '--output', nargs=2, action='append')

Then -o output1 text -o output2 csv

will produce something like

args = p.parse_args(['-o', 'output1', 'text', '-o', 'output2', 'csv'])
assert args.output == [['output1', 'text'], ['output2', 'csv']]

You can post-process args.output to get the desired dict, or define a custom Action whose __call__ method will build the dict value itself.



来源:https://stackoverflow.com/questions/48504770/argparse-associate-arguments-with-another-argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!