On 23 November 2012 18:46, Roy Smith <span dir="ltr"><<a href="mailto:roy@panix.com" target="_blank">roy@panix.com</a>></span> wrote:<br><div class="gmail_extra"><div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex">


My command either takes two positional arguments (in which case, both<br>
are required):<br>
<br>
$ command foo bar<br>
<br>
or the name of a config file (in which case, the positional arguments<br>
are forbidden):<br>
<br>
$ command --config file<br>
<br>
How can I represent this with argparse; add_mutually_exclusive_group()<br>
isn't quite the right thing.  It could specify that foo and --config are<br>
mutually exclusive, but not (as far as I can see) the more complicated<br>
logic described above.</blockquote><div><br></div><div>Do you need to use argparse?</div><div><br></div><div>If not, I've been recommending docopt due to its power and simplicity:</div><div><br></div><div>-----START -----</div>


<div><div><div>""" </div><div>Command.</div><div><br></div><div>Usage:</div><div>    command <foo> <bar></div><div>    command --config=<file></div><div><br></div><div>Options:</div><div>

    foo              The egg that spams</div>
<div>    bar              The spam that eggs</div><div>    --config=<file>  The config that configures</div><div>"""</div><div><br></div><div>from docopt import docopt</div><div><br></div><div>if __name__ == '__main__':</div>


<div>    arguments = docopt(__doc__)</div><div>    print(arguments)</div></div></div></div><div class="gmail_extra">----- END ----</div><div class="gmail_extra"><br></div><div class="gmail_extra">----- USAGE -----</div><div class="gmail_extra">


<div class="gmail_extra"><div>%~> python simple_docopt.py foobar barfoo</div><div>{'--config': None,</div><div> '<bar>': 'barfoo',</div><div> '<foo>': 'foobar'}</div>

<div>%~> python simple_docopt.py foobar</div><div>Usage:</div><div>    simple_docopt.py <foo> <bar></div><div>    simple_docopt.py --config=<file></div><div>%~> python simple_docopt.py --config=turtle.conf</div>

<div>{'--config': 'turtle.conf',</div><div> '<bar>': None,</div><div> '<foo>': None}</div><div>%~> python simple_docopt.py --config=turtle.conf not allowed</div><div>Usage:</div>

<div>    simple_docopt.py <foo> <bar></div><div>    simple_docopt.py --config=<file></div></div><div class="gmail_extra">------- END USAGE -------</div></div></div>