Hmmm, Beazley book missing something?

Alex Martelli alex at magenta.com
Tue Aug 1 17:20:03 EDT 2000


"Steve Lamb" <grey at despair.rpglink.com> wrote in message
news:slrn8oed8k.3li.grey at teleute.rpglink.com...
>     Ok, trying to get a basic read loop going for stdin in Python.  If I
may
> explain in perl.
>
> while (<>){
>   do_meaningful_crap_here();
> }

import fileinput

for line in fileinput.input():
    do_whatever_to_the_line(line)


Note that the input function of the fileinput module also has optional
arguments to do in-place replacement of input files (like Perl's -i)
possibly while backing them up (like Perl's -i.bak), and the module
has other helpful functions to find out the name of the file you're
currently reading, etc, etc.  In other words, the functionality is
really quite close to Perl's while(<>) & friends:-).

Like Perl's while(<>), fileinput.input() is not limited to sys.stdin,
but rather will read the files named in sys.argv[1:] (using sys.stdin
only if that sublist of the arguments is empty).  If you do want
to use sys.stdin, whatever args the program was called with, you can
sys.argv[1:]=[] (if you have already processed those args and do
not care about them any more), or use other loop idioms such as:

for line in sys.stdin.readlines():
    do_whatever_to_the_line(line)

This offers a bit less functionality (e.g., it doesn't count the
total number of lines processed so far), but it's often OK too.


>     Look up stdin in the Beazley book and note that it has a basic routine
for
> reading stdin character by character.  That can't be right.  So I check
dir()
> on sys and then sys.stdin
>
> >>> dir(sys.stdin)
> ['close', 'closed', 'fileno', 'flush', 'isatty', 'mode', 'name', 'read',
> 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell',
> 'truncate', 'write', 'writelines']
>
>     I see readline and readlines in there.  Only mention of it is in the
> multifile object.  No __doc__ string for those methods, either.  Did this
get
> overlooked in this book?

Sorry, dunno about the book.  All of these methods are those of built-in
fileobjects, of which sys.stdin is one, and you can read about them in
"2.1.7.9 File Objects" in the Library Reference docs.


Alex






More information about the Python-list mailing list