argparse limitations

Peter Otten __peter__ at web.de
Fri Jul 27 11:44:44 EDT 2012


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?





More information about the Python-list mailing list