argparse -- mutually exclusive sets of arguments?

R

Roy Smith

My command either takes two positional arguments (in which case, both
are required):

$ command foo bar

or the name of a config file (in which case, the positional arguments
are forbidden):

$ command --config file

How can I represent this with argparse; add_mutually_exclusive_group()
isn't quite the right thing. It could specify that foo and --config are
mutually exclusive, but not (as far as I can see) the more complicated
logic described above.
 
T

Terry Reedy

My command either takes two positional arguments (in which case, both
are required):

$ command foo bar

or the name of a config file (in which case, the positional arguments
are forbidden):

$ command --config file

How can I represent this with argparse; add_mutually_exclusive_group()
isn't quite the right thing. It could specify that foo and --config are
mutually exclusive, but not (as far as I can see) the more complicated
logic described above.

Make the two positional arguments be one duple?
Or tell argparse that all three are optional and handle the 'more
complicated logic' in your own code after argparse returns.
 
I

Ian Kelly

My command either takes two positional arguments (in which case, both
are required):

$ command foo bar

or the name of a config file (in which case, the positional arguments
are forbidden):

$ command --config file

How can I represent this with argparse; add_mutually_exclusive_group()
isn't quite the right thing. It could specify that foo and --config are
mutually exclusive, but not (as far as I can see) the more complicated
logic described above.

I don't think you could even do the former. An argument must be
optional in order to be mutually exclusive with anything. This works,
however:

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--config', type=file)
group.add_argument('--foobar', nargs=2, metavar=('FOO', 'BAR'))
print parser.parse_args()

Downsides are that the resulting interface is a little more formal and
a little less friendly, and unless you customize the action you'll
wind up with a 2-element 'foobar' arg instead of separate 'foo' and
'bar' args.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top