Johnny Metz
Johnny Metz

Reputation: 5965

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 argparse.py (with no arguments) and argparse.py --a to return the same output.

Upvotes: 0

Views: 815

Answers (1)

hpaulj
hpaulj

Reputation: 231395

I would just add a simple test after parsing

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

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.

Upvotes: 1

Related Questions