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
2
  • The program hangs at the second line of the loop and doesn't quit unless I interrupt it with the keyboard. Commented Mar 6, 2012 at 17:53
  • 2
    Are you sure your file ends with a '\n' line? You're probably running into an infinite loop here. It's likely that your file ends with a '' line. Commented Mar 6, 2012 at 17:53

3 Answers 3

16

As others have mentioned, probably your condition line == '\n' never holds true. The proper solution would be to use a loop like:

for line in sys.stdin:
  stripped = line.strip()
  if not stripped: break
  lines.append(stripped)
Sign up to request clarification or add additional context in comments.

Comments

14

Consider the following option

import sys
sys.stdin = open("input.txt", "r")

Comments

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

1 Comment

How is that supposed to help??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.