[Tutor] read from standard input
john at fouhy.net
Thu Feb 14 05:27:28 CET 2008
On 14/02/2008, Andrei Petre <andrei.petre at gmail.com> wrote:
> 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:
> while 1 < 2:
> x = raw_input()
> if type(x) != int or x == 11:
> print x
This won't work because raw_input() always returns a string. The
pythonic way to make that code work is:
raw_x = raw_input()
x = int(raw_x)
if x == 11:
(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:
special = 11
for line in sys.stdin:
x = int(line)
print 'Bad input.'
if x == special:
print 'Special value reached.'
print 'End of input reached.'
More information about the Tutor