Exeleration-G Exeleration-G - 2 months ago 13
Python Question

Python Argparse "radio" flags with default?

For example:

example.py


parser = argparse.ArgumentParser(description="Will take arguments... or none")

parser.add_argument("-a", action="store_true")
parser.add_argument("-b", action="store_true")
parser.add_argument("-c", action="store_true")
parser.add_argument("-d", action="store_true")

args = parser.parse_args()
print args


I want example.py to set
a
to
True
, but only if either:


  • The
    -a
    flag is used

  • No flags are used



I tried messing around with

parser.set_defaults(a=True, b=False)


and

parser.add_argument("-a", action="store_true", default=True)


but they will set
a
to
True
even if I decide to use the
b
flag.

Answer

yes using the default values will set a to True even other arguments are specified. This will violate your second requirement, following is a simple fix with a naive condition checking.

parser = argparse.ArgumentParser(description="Will take arguments... or none")

parser.add_argument("-a", action="store_true")
parser.add_argument("-b", action="store_true")
parser.add_argument("-c", action="store_true")
parser.add_argument("-d", action="store_true")

args = parser.parse_args()
if not (args.b or args.c or args.d):
    args.a=True
print args
Comments