我有問題需要從標準輸入或管道讀取python時,管道是來自「打開」(不知道正確的名稱) 文件。如何從一個沒有結尾的管道在Python中讀取stdin
我爲例 pipetest.py:
import sys
import time
k = 0
try:
for line in sys.stdin:
k = k + 1
print line
except KeyboardInterrupt:
sys.stdout.flush()
pass
print k
我運行有繼續輸出,並經過一段時間
$ ping 127.0.0.1 | python pipetest.py
^C0
我沒有得到任何輸出按Ctrl + C的程序。 但如果我通過一個普通的文件去它的作品。
$ ping 127.0.0.1 > testfile.txt
這是按Ctrl + C經過短暫的結束而
$ cat testfile.txt | python pipetest.py
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.017 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.015 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.014 ms
64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.013 ms
64 bytes from 127.0.0.1: icmp_seq=5 ttl=64 time=0.012 ms
--- 127.0.0.1 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 3998ms
rtt min/avg/max/mdev = 0.012/0.014/0.017/0.003 ms
10
我怎樣做節目結束之前,在這種情況下,中國平安已經結束得到任何輸出?
我很高興它的工作,但你肯定可以用`在stdin`行,只要你知道它會阻止,直到找到結束的行(這就是爲什麼你的版本的作品,`read`不會像那樣阻止)。 – agf 2011-08-17 10:55:49
我不是建議你刪除你的答案,只是最後一行是錯誤的。我刪除了「完全錯誤」的評論,因爲它是錯誤的 - 你的程序是正確的,只是你的結語是錯誤的。我不是downvoter(我不會,因爲我不知道你的答案是否會起作用)。 – agf 2011-08-17 11:06:08