stdin or optional fileinput
Steven Bethard
steven.bethard at gmail.com
Wed Mar 15 11:30:15 EST 2006
the.theorist wrote:
> I was writing a small script the other day with the following CLI
> prog [options] [file]*
>
> I've used getopt to parse out the possible options, so we'll ignore
> that part, and assume for the rest of the discussion that args is a
> list of file names (if any provided).
>
> I used this bit of code to detect wether i want stdinput or not.
>
> if len(args)==0:
> args = [ sys.stdin ]
>
> Now in my main loop I've written:
>
> for file in args:
> for line in open( file ):
> #do stuff
You should probably write:
if not args: # note that len(args) == 0 is repetitively redundant, over
# and over again, in a reiterative manner
files = [sys.stdin]
else:
files = (open(filename) for filename in args)
...
for fileobj in files: # using the name 'file' is a bad idea since it
# shadows the builtin 'file'
for line in fileobj:
# do stuff
STeVe
More information about the Python-list
mailing list