Mutually exclusive option groups

23 views
Skip to first unread message

Scott Armitage

unread,
Jan 6, 2011, 5:03:41 PM1/6/11
to argparse-users
Greetings argparse-users,

I am writing my first (legitimate) command-line application, to be
used with in-house device development (it is a specialized terminal
program for communicating with microcontroller devices). I have opted
to use the new argparse module for working with my command line
arguments, and so far I am very pleased with how easy it is to use.

I do have one question, however:

I have two methods different ways for specifying a device:
--g1opt1 --g1opt2 --g1opt3
and
--g2opt1 --g2opt2

Basically, either the user needs to specify all three of g1optX, or
both of g2optX; if at least one option is given from both of these
groups, it is an ArgumentError.

Is there a way to do this within argparse itself? If not, I can just
do a simple check with e.g.
if any(g1opt1,g1opt2,g1opt3) and any(g2opt1,g2opt2):
raise ...
but in that case, how exactly can I raise an exception such that the
error messaging looks the same as argparse's natural parsing errors?

Steven Bethard

unread,
Jan 7, 2011, 11:26:46 AM1/7/11
to argpars...@googlegroups.com
On Thu, Jan 6, 2011 at 3:03 PM, Scott Armitage <scott.a...@gmail.com> wrote:
> I have two methods different ways for specifying a device:
>     --g1opt1 --g1opt2 --g1opt3
> and
>     --g2opt1 --g2opt2
>
> Basically, either the user needs to specify all three of g1optX, or
> both of g2optX; if at least one option is given from both of these
> groups, it is an ArgumentError.
>
> Is there a way to do this within argparse itself? If not, I can just
> do a simple check with e.g.
>    if any(g1opt1,g1opt2,g1opt3) and any(g2opt1,g2opt2):
>        raise ...

There's currently no way to specify something like this - argparse
doesn't know how to say that two groups of options are mutually
exclusive. So yeah, you'll have to do your check above.

> but in that case, how exactly can I raise an exception such that the
> error messaging looks the same as argparse's natural parsing errors?

I think you just want to call parser.error(message):

http://docs.python.org/dev/library/argparse.html#argparse.ArgumentParser.error

Steve
--
Where did you get that preposterous hypothesis?
Did Steve tell you that?
        --- The Hiphopopotamus

Reply all
Reply to author
Forward
0 new messages