Silly question re: 'for i in sys.stdin'?
Jeff Epler
jepler at unpythonic.net
Sun Apr 3 22:59:48 EDT 2005
The iterator for files is a little bit like this generator function:
def lines(f):
while 1:
chunk = f.readlines(sizehint)
for line in chunk: yield line
Inside file.readlines, the read from the tty will block until sizehint
bytes have been read or EOF is seen.
If you want this kind of line-at-a-time functionality, then you could
use the iter(callable, sentinel) form, and switch between it and the
readlines method based on a commandline flag or whether the file
satisfies 'os.isatty()':
def lines(f): # untested
"""lines(f)
If f is a terminal, then return an iterator that gives a value after
each line is entered. Otherwise, return the efficient iterator for
files."""
if hasattr(f, "fileno") and isatty(f.fileno()):
return iter(f.readline, '')
return iter(f)
for line in lines(sys.stdin):
doSomethingWith(line)
Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20050403/a2f2bf49/attachment.sig>
More information about the Python-list
mailing list