[Tutor] read from standard input

John Fouhy john at fouhy.net
Thu Feb 14 05:27:28 CET 2008


On 14/02/2008, Andrei Petre <andrei.petre at gmail.com> wrote:
> Hello,
>
> I want to read from the standard input numbers until i reach a certain value
> or to the end of the "file".
> What is the simplest, straightforward, pythonic way to do it?
>
> a sketch of how i tried to do it:
> [code]
> while 1 < 2:
>     x = raw_input()
>     if type(x) != int or x == 11:
>         break
>     else:
>         print x
>  [/code]

This won't work because raw_input() always returns a string.  The
pythonic way to make that code work is:

while True:
  raw_x = raw_input()
  try:
    x = int(raw_x)
  except ValueError:
    break
  if x == 11:
    break
  print x

(actually, you would be better giving x an initial value and then
writing 'while x != 11' ..)

> but don't work. and i'm interest in a general way to read until it is
> nothing to read.

sys.stdin is a file-like object corresponding to standard in.  You can do this:

import sys
special = 11
for line in sys.stdin:
  try:
    x = int(line)
  except ValueError:
    print 'Bad input.'
    break
  if x == special:
    print 'Special value reached.'
    break
else:
  print 'End of input reached.'

-- 
John.


More information about the Tutor mailing list