Steven Bethard wrote:
> 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
I'll keep both those in mind for future programs.
my current fix has been
if not args:
args = [ sys.stdin ]
else:
map( open, args )
and then a modification to the main loop, as you proposed.
I thought that one day I might run into a problem opening too many
files though (esp if i used xargs in a pipe). And it just _feels_
better to open and close as I loop over the files list, rather than
open everything at the get go.
OH, i've noticed you used a generator that takes care of that. Except,
the machine I'm working on is currently stuck at Python 2.3. Still,
I'll keep your suggestions in mind for future coding.
--
http://mail.python.org/mailman/listinfo/python-list