input

D-Man dsh8290 at rit.edu
Wed May 30 15:25:54 EDT 2001


On Wed, May 30, 2001 at 06:47:13PM +0000, mjt at dhcp-177-003.cns.ohiou.edu wrote:
| I'm curious about reading input in python.  It seems like there should be
| a fast way to read input closer to the way C or C++ reads input.  I like
| the way input functions help the programmer read in formatted input.  Is
| there a good way to do it in Python?

(IMO) C doesn't do a good job of reading arbitrary amounts of input
without risking random memory corruption.  Java provides no mechanism
at all (aside from reading into pre-made byte arrays, which are
obviously of a fixed length).

Python has  'raw_input'  which returns the string read from input up
to End-Of-Line.  It doesn't tinker with the string at all.  'input'
shouldn't be used because it is

    def input() :
        return eval( raw_input() )

and if the user has a bad disposition they can wreak havoc on your
application's innards, or foul up the host system.

If you have a file handle (import sys ; print sys.stdin) you can use
the read( [maxhint] ) or readline() methods to read the whole buffer
(up to [maxhint], if specified) or just the next line.  There are also
readlines( [maxhint] ) and xreadlines( [maxhint] ) methods to return a
list of lines, up to maxhint if specified.  (xreadlines is a
performance optimization similar to xrange)

HTH,
-D






More information about the Python-list mailing list