Reading input from redirected stdin using python

I have this loop that reads lines from stdin before entering a new line, however this only works from input to input. How to get a program to read lines from a redirected stdin through a command line?

For instance:

$ python graph.py < input.input 

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

 while 1: line = sys.stdin.readline() if line == '\n': break try: lines.append(line.strip()) except: pass 
+4
source share
2 answers

As others have already noted, your line == '\n' state may never be executed. The correct solution would be to use a loop such as:

 for line in sys.stdin: stripped = line.strip() if not stripped: break lines.append(stripped) 
+11
source

ETA: based on your comment that you work in an infinite loop, you probably just don't have an empty line at the end of the file.


Use pipe symbol:

 input.input | python graph.py 

If input.input is actually a file, not a stream, use cat to create a stream from it:

 cat input.input | python graph.py 
+1
source

Source: https://habr.com/ru/post/1208437/


All Articles