stdin or optional fileinput

Peter Otten __peter__ at web.de
Wed Mar 15 13:45:36 EST 2006


the.theorist wrote:

> 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.

use

if args:
    args = itertools.imap(open, args)
else:
    args = [sys.stdin]

to get the same lazy-open behaviour as with the generator expression.
Or have a look at http://docs.python.org/lib/module-fileinput.html.

Peter



More information about the Python-list mailing list