2015-10-18 44 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。奇怪! –