2015-10-18 62 views
0

我有如下一个简单的Python程序:在sys.stdin行不返回任何值

import sys 

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

我与OS X埃尔卡皮坦一个MAC工作。我有Python 2.7.10

当我在终端上的程序上运行它时,它挂起。它不打印行。

下图描述了该问题。该命令已在终端运行超过5分钟,但没有输出

请帮我理解问题。

感谢 Image of the terminal

+1

命令行参数!= STDIN。 –

回答

1

你的代码是试图从标准输入读取,这意味着你需要至少pipe东西到标准输入,在这里我稍微改变你的代码和script.py后,将其命名为:

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

这里是在外壳的输出:

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

的标准输入,标准输出和ERR为叔一般来说,UNIX中的重要概念,我建议你阅读more。举例来说,Hadoop Streaming实际上利用stdin/stdout,因此您可以使用任何语言编写map reduce作业,并轻松地将不同的组件连接在一起。

这里有几个如何让你的代码工作的例子,如果你有一个文件。

$ 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) 
+0

谢谢。那有效,但这是我第一次以这种方式使用它。在之前它使用没有管道的stdin。奇怪! –