jcmetz21 jcmetz21 - 4 months ago 13
Python Question

argparse: make one argument default when no arguments are called

What's the best way to set a group argument as the default when no arguments are called.

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("--a", action="store_true") #call when no arguments are provided
group.add_argument("--b", action="store_true")
group.add_argument("--c", action="store_true")

Let's call my program argparse_ex.py. I want
(with no arguments) and
argparse.py --a
to return the same output.


I would just add a simple test after parsing

if not any([args.a, args.b, args.c]):

This is simpler than any attempt to make parse_args to do this. The parser will parse all arguments independently - and in any order. So you really can't tell until the parsing is all done whether any of the options has been selected or not.