argparse limitations

Benoist Laurent benoist at ibpc.fr
Fri Jul 27 13:08:29 EDT 2012



Yes basically looks like you get it.
I have to further test it but my first impression is that it's correct.

So actually the point was to use nargs="?".

Thank you very much.
Ben



Le Jul 27, 2012 à 5:44 PM, Peter Otten a écrit :

> Benoist Laurent wrote:
> 
>> 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
> 
> $ echo alpha > in.txt
> $ cat in.txt | ./mytool.py 
> ALPHA
> $ cat in.txt | ./mytool.py - out.txt
> $ cat out.txt 
> ALPHA
> $ ./mytool.py in.txt 
> ALPHA
> $ ./mytool.py in.txt out2.txt
> $ cat out2.txt 
> ALPHA
> $ cat ./mytool.py
> #!/usr/bin/env python
> assert __name__ == "__main__"
> 
> import argparse
> import sys
> 
> parser = argparse.ArgumentParser()
> parser.add_argument("infile", nargs="?", type=argparse.FileType("r"), 
> default=sys.stdin)
> parser.add_argument("outfile", nargs="?", type=argparse.FileType("w"), 
> default=sys.stdout)
> args = parser.parse_args()
> 
> args.outfile.writelines(line.upper() for line in args.infile)
> 
> Is that good enough?
> 
> 
> -- 
> 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/0acfd7ef/attachment.html>


More information about the Python-list mailing list