Alex Rivera | Logout

Read input from redirected stdin with python

Asked 2012-03-06T17:47:36.453
11

I have this loop that reads lines from stdin until a newline is entered, however, this only works from typing in the input. How do I get the program to read lines from a redirected stdin via the command line?

For instance:

$ python graph.py < input.input

Here is the loop I have to read lines from input:

while 1:
     line = sys.stdin.readline()
     if line == '\n':
         break
     try:
       lines.append(line.strip())
     except:
       pass
Edit
Report

1 Answer

3

ETA: Based on your comment that you're running into an infinite loop, you probably just don't have an empty line at the end of the file.


Use a pipe character:

input.input | python graph.py

If input.input is in fact a file rather than a stream, use cat to create a stream from it:

cat input.input | python graph.py
answered 2012-03-06T17:52:21.910

Your Answer