On 1/24/13, Peter Otten <__pete...@web.de> wrote: > Santosh Kumar wrote: > >> Yes, Peter got it right. >> >> Now, how can I replace: >> >> script, givenfile = argv >> >> with something better that takes argv[1] as input file as well as >> reads input from stdin. >> >> By input from stdin, I mean that currently when I do `cat foo.txt | >> capitalizr` it throws a ValueError error: >> >> Traceback (most recent call last): >> File "/home/santosh/bin/capitalizr", line 16, in <module> >> script, givenfile = argv >> ValueError: need more than 1 value to unpack >> >> I want both input methods. > > You can use argparse and its FileType: > > import argparse > import sys > > parser = argparse.ArgumentParser() > parser.add_argument("infile", type=argparse.FileType("r"), nargs="?", > default=sys.stdin) > args = parser.parse_args() > > for line in args.infile: > print line.strip().title() # replace with your code >
This works file when I do `script.py inputfile.txt`; capitalizes as expected. But it work unexpected if I do `cat inputfile.txt | script.py`; leaves the first word of each line and then capitalizes remaining. -- http://mail.python.org/mailman/listinfo/python-list