argparse limitations

Benoist Laurent benoist at ibpc.fr
Fri Jul 27 17:19:04 CEST 2012


Le Jul 27, 2012 à 4:43 PM, Oscar Benjamin a écrit :

> 
> 
> On 27 July 2012 15:26, Benoist Laurent <benoist at ibpc.fr> wrote:
> Hi,
> 
> I'm impletting a tool in Python.
> I'd like this tool to behave like a standard unix tool, as grep for exemple.
> I chose to use the argparse module to parse the command line and I think I'm getting into several limitations of this module.
> 
> > First Question.
> How can I configure the the ArgumentParser to allow the user to give either an input file or to pipe the output from another program?
> 
> $ mytool.py file.txt 
> $ cat file.txt | mytool.py
>  
> A better way to do that last line is:
> $ mytool.py < file.txt 
> 
> To answer the question, just make the first argument optional defaulting to None. Then you can do:
> if file1 is None:
>     file1 = sys.stdin

That's the solution I came to.
But I'm not very happy with this since I can definitively not make my program act as a standard unix tool.
Any other solution?


>  
> 
> 
> > Second Question.
> How can I get the nargs options working with subparser?
> Cause basically if I've got a positionnal argument with nargs > 1, then the subparsers are recognized as values for the positionnal argument.
> 
> $ mytool.py file1.txt file2.txt foo
> 
> Here foo is a command I'd like to pass to mytool but argparse considers it's another input file (as are file1.txt and file2.txt).
> 
> I haven't used subparsers in argparse but I imagine that you would call it like:
> $ mytool.py foo file1.txt file2.txt

As far as I know it is not the case.
Let's get into the code.

parser = argparse.ArgumentParser()
parser.add_argument("-i", help="input files", nargs="+")

subparsers = parser.add_subparsers() 
foo_parser = subparser.add_parser("foo")
# ... here come some foo parser options
bar_parser = subparser.add_parser("bar")
# ... here come some bar parser options

What argparse expects is the "-i" arguments coming before the subparsers.

To summarize, if I adopt your solution to my first question, the I should add the "-i" argument to each subparser.
I don't want to since it's ugly and I'd have to write the help myself (which I don't want to).


Cheers


>  
> 
> Cheers,
> Oscar.
> 
> 
> 
> Any help would be appreciated.
> Ben.
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

-- 
Benoist Laurent
Laboratoire de Biochimie Theorique / CNRS UPR 9080
Institut de Biologie Physico-Chimique
13, rue Pierre et Marie Curie
F-75005 Paris
Tel. +33 [0]1 58 41 51 67 or +33 [0]6 21 64 50 56

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120727/a37c41d4/attachment.html>


More information about the Python-list mailing list