tags:

views:

415

answers:

6

I usually do this in Perl:

whatever.pl

while(<>) {
    #do whatever;
}

then cat foo.txt | whatever.pl

Now, I want to do this in Python. I tried sys.stdin but I have no idea how to do as I have done in Perl. How can I read the input?

Thanks.

EDIT:

Thanks, I like every single solution.

+19  A: 

Try this:

import fileinput
for line in fileinput.input():
    process(line)
Don Werve
+1: fileinput is way cool.
S.Lott
+1 This way is more flexible than "for line in sys.stdin", as it will work for filenames pass as cmd line arguments.
+4  A: 
import sys
def main():
    for line in sys.stdin:
        print line
if __name__=='__main__':
    sys.exit(main())
Mark Roddy
-1: main returns None -- it's not *perfectly* clear what value should be returned to the OS.
S.Lott
@S.Lott: It is perfectly clear how sys.exit treats None.
Roger Pate
+3  A: 

Something like this:

import sys

for line in sys.stdin:
    # whatever
David Zaslavsky
+3  A: 
import sys

for line in sys.stdin:
    # do stuff w/line
Can Berk Güder
+1  A: 

You may find a Rosetta Stone helpful. I tend to use http://www.lurklurk.org/rosetta.html.

Chas. Owens
A: 

Hi i want to do the same in groovy. any suggestion how can i do it?

Shuja
This isn't an answer to the question. You should probably make your own question, and reference this one.
Epcylon