0

I have a simple python program as below:

import sys

for line in sys.stdin.readlines():
    print (line)

I am working on a mac with os x el capitan. I have Python 2.7.10

When I run this on the program on the terminal, it hangs. It does not print the line.

The image below describes the issue. The command has been running in the terminal fro more than 5 min, yet no outuput

Please help me understand the issue.

Thanks Image of the terminal

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
zappy
  • 33
  • 1
  • 5

1 Answers1

1

Your code is trying to read from stdin, which means you need to at least pipe something into the stdin, here I changed your code slightly and named it after script.py:

import sys
for line in sys.stdin.readlines():
    print (line,1)

And here is the output in shell:

$printf "hello\nworld\n" | python script.py
('hello\n', 1)
('world\n', 1)

The stdin, stdout, and err are three important concepts in unix in general, i would recommend you to read more about it. Say for example, Hadoop Streaming actually leverage stdin/stdout so you can use any language to write map reduce jobs and easily connect different components together.

Here are a few examples of how to get your code working if you have a file.

$ printf "hello\nworld\n" > text
$ cat text
hello
world
$ cat text | python script.py 
('hello\n', 1)
('world\n', 1)
$ python script.py < text
('hello\n', 1)
('world\n', 1)
B.Mr.W.
  • 18,910
  • 35
  • 114
  • 178
  • Thanks. that worked, But this is the first time I am using it this way. Before it used to take the stdin without pipe. surprising! – zappy Oct 18 '15 at 17:06