简体   繁体   中英

Setting default value for optional argument that depends on another optional argument in python argparse

I am using python argparse() for command line parsing. I want something like this,

-a -> optional argument

-b -> optional argument that depends on a with default value x

Condition : -b should set(either to default or custom value) if and only if a is set, otherwise b should be None .

Could someone help me to achieve this?

@hpaulj 's comment still holds. This is best done in code after parsing

But you could do it with the @property and your own MyNamespace object instead of default argparse namespace

The @property lets you write arbitrary code for getters/setters of a particular class object (in this case b)

class MyNamespace(object):
    def __init__(self):
        self.a = None
        self._b = None   # this is a variable to store the actual value of -b

    @property
    def b(self):
        if self.a:
            return "A_IS_SET"
        else:
            return self._b or None
    @b.setter
    def b(self, input):
        self._b = input

def parse():
    parse.avalue = []
    parse.bvalue = []

    parser = argparse.ArgumentParser()
    parser.add_argument("-a")
    parser.add_argument("-b")

    out = parser.parse_args(namespace=MyNamespace())
    print out.a, out.b

if __name__ == "__main__":
    parse()
When both a, b are passed (in any order)
$>python testparse.py -b BTEST 
None BTEST
$>python testparse.py -a atest
atest A_IS_SET
When only -b is passed
$>python testparse.py -b BTEST None BTEST
When only -a is passed
$>python testparse.py -a atest atest A_IS_SET
When none of them is passed
$>python testparse.py None None

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM