On 23 November 2012 18:46, Roy Smith <[email protected]> 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 -------
--
http://mail.python.org/mailman/listinfo/python-list