argparse -- mutually exclusive sets of arguments?

Joshua Landau joshua.landau.ws at gmail.com
Fri Nov 23 18:49:03 EST 2012


On 23 November 2012 18:46, Roy Smith <roy at panix.com> 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.

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

Options:
    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__)
    print(arguments)
----- END ----

----- USAGE -----
%~> python simple_docopt.py foobar barfoo
{'--config': None,
 '<bar>': 'barfoo',
 '<foo>': 'foobar'}
%~> python simple_docopt.py foobar
Usage:
    simple_docopt.py <foo> <bar>
    simple_docopt.py --config=<file>
%~> python simple_docopt.py --config=turtle.conf
{'--config': 'turtle.conf',
 '<bar>': None,
 '<foo>': None}
%~> python simple_docopt.py --config=turtle.conf not allowed
Usage:
    simple_docopt.py <foo> <bar>
    simple_docopt.py --config=<file>
------- END USAGE -------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20121123/ca28aaf4/attachment.html>


More information about the Python-list mailing list