Python ArgumentParser nested arguments

不羁的心 提交于 2019-12-22 08:11:58

问题


I want to create argument parser with following signature:

./myapp [-a [-b BVAL] | -c]

In other words, user could provide argument -b BVAL only in case if he provided argument -a.

It's quite easy to create mutually exclusive group of -a and -c, but I can't figure out how to create relationship allow -b only if -a provided


回答1:


You could inherit from ArgumentParser to add some custom functionality. Here I am raising an exception, but you could modify this to implement whatever you would like. Just change the on_dependency_error() method to suit your needs.

from argparse import ArgumentParser

class FancyParser(ArgumentParser):
    # {'b': 'a'} Where b depends on a
    dependencies = {}

    def on_dependency_error(self, arg, depends_on):
        raise FancyParser.DependencyError(
                    'Argument %s depends on %s' % (arg, depends_on))

    def add_argument(self, *args, **kwargs):
        depends_on = kwargs.get('depends_on')
        if depends_on:
            self.dependencies[kwargs.get('dest') or args[0]] = depends_on
            del kwargs['depends_on']
        return super(FancyParser, self).add_argument(*args, **kwargs)

    def parse_args(self, *args, **kwargs):
        args = super(FancyParser, self).parse_args(*args, **kwargs)
        for arg, depends_on in self.dependencies.iteritems():
            if getattr(args, arg) and not getattr(args, depends_on):
                self.on_dependency_error(arg, depends_on)
        return args

    class DependencyError(Exception):
        def __init__(self, *args, **kwargs):
            return super(FancyParser.DependencyError,
                         self).__init__(*args, **kwargs)

You can then use it like this -

args = ['-a', '-b', 'BVAL', '-c']
parser = FancyParser()
parser.add_argument('-a', dest='a', action='store_true')
parser.add_argument('-b', dest='b', depends_on='a')
parser.add_argument('-c', dest='c', action='store_true')
try:
    parser.parse_args(args)
except FancyParser.DependencyError as e:
    # Whatever here...
    pass



回答2:


Docopt does it just as I wanted. Terrific!

docopt('./myapp [-a [-b BVAL] | -c]')



回答3:


It's not exactly what you're looking for but maybe what you could use add_subparsers() (doc)?

Do something like:

import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='sub-command help')
a = subparsers.add_parser('a')
c = subparsers.add_parser('c')
a.add_argument('b')



回答4:


If you don't want to use subparsers, you can handle your argument values yourself using parser.error.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a', dest='a', default='')  # you can use other defaults surely
parser.add_argument('-b', dest='b', default='')
parser.add_argument('-c', dest='c', default='')

args = parser.parse_args()

if args.b and not args.a:
    parser.error("Option 'b' can't be specified without 'a'")

But still consider using subparsers in case you might extend the logic



来源:https://stackoverflow.com/questions/13788333/python-argumentparser-nested-arguments

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