oscar.j.benjamin at gmail.com
Tue Jul 31 15:04:53 CEST 2012
On 31 July 2012 13:51, Benoist Laurent <benoist at ibpc.fr> wrote:
> Le Jul 31, 2012 à 1:45 PM, Oscar Benjamin a écrit :
> On 31 July 2012 12:03, Benoist Laurent <benoist at ibpc.fr> wrote:
>> The code I proposed doesn't work in this case: if you add any positional
>> argument to one of the subparsers, then the parsing doesn't work anymore.
>> The reason seems to be that argparse thinks the last argument of the
>> first parser is the last but one argument.
>> Hence, if a subparser takes some arguments, it fails.
>> Example: if the "-n" argument of the foo parser is set mandatory (so
>> becomes "n" instead of "-n")
>> python toto.py foo.txt bar.txt foo 10
>> usage: toto.py [-h] [fname [fname ...]] command ...
>> toto.py: error: argument command: invalid choice: '10' (choose from
>> 'foo', 'bar')
> What about:
> $ python toto.py foo.txt bar.txt foo -n 10
> Note that contrary to what you said above, your program does not work like
> a "standard unix tool". A standard command line program to do what you want
> would normally look like
> You're right.
> But then, using argparse, I would have to add the same argument to all my
> subparsers since argparse does the work sequentially: once it recognized
> the start of a subparser, everything that follows have to be an argument of
> this subparser.
> Hence, arguments (therefore options) from the main parser are not
> recognized anymore.
If the parsing after the subcommand is to be the same for each subcommand,
then don't use subparsers. You could just make the first argument be the
command name and use one parser for everything.
If the parsing is supposed to be different for different subcommands then
use subparsers and add the files argument to each subparser; you can make a
function to add the common arguments and options if you don't want to
duplicate the code.
Well I guess it is a intrinsec limitation: I think it's quite natural that
> the user can't enter a filename named as a command.
There is an intrinsic limitation on any parser that it must be possible to
determine the targets of the arguments uniquely. If you want the parser to
scan through and take the first argument matching 'foo' or 'bar' and parse
the remaining arguments accordingly then you already have your solution. It
just won't work if the user wants to pass in a file called 'foo' or 'bar'
(maybe that's acceptable, though).
The standard way, however, is to have a parser that takes the first
non-option argument as a subcommand name and parses the remaining arguments
according to that subcommand. Your command line users are more likely to be
able to understand how to use the program if it works that way.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list