Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read input from redirected stdin with python

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
like image 512
Christian Benincasa Avatar asked Mar 06 '12 17:03

Christian Benincasa


2 Answers

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)
like image 151
Niklas B. Avatar answered Oct 05 '22 12:10

Niklas B.


Consider the following option

import sys
sys.stdin = open("input.txt", "r")
like image 41
1memine Avatar answered Oct 05 '22 12:10

1memine