argparse -- mutually exclusive sets of arguments?

Joshua Landau at
Sat Nov 24 00:49:03 CET 2012

On 23 November 2012 18:46, Roy Smith <roy at> wrote:

> 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.

Do you need to use argparse?

If not, I've been recommending docopt due to its power and simplicity:

-----START -----

    command <foo> <bar>
    command --config=<file>

    foo              The egg that spams
    bar              The spam that eggs
    --config=<file>  The config that configures

from docopt import docopt

if __name__ == '__main__':
    arguments = docopt(__doc__)
----- END ----

----- USAGE -----
%~> python foobar barfoo
{'--config': None,
 '<bar>': 'barfoo',
 '<foo>': 'foobar'}
%~> python foobar
Usage: <foo> <bar> --config=<file>
%~> python --config=turtle.conf
{'--config': 'turtle.conf',
 '<bar>': None,
 '<foo>': None}
%~> python --config=turtle.conf not allowed
Usage: <foo> <bar> --config=<file>
------- END USAGE -------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list