您如何从没有结尾的管道中读取python中的stdin [英] How do you read from stdin in python from a pipe which has no ending
本文介绍了您如何从没有结尾的管道中读取python中的stdin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当管道来自"open"(不知道正确的名称)时,我无法从python的标准输入或管道中读取数据 文件.
I've problem to read from Standard input or pipe in python when the pipe is from a "open" (do not know right name) file.
我举个例子 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
我运行的程序经过一段时间后会继续输出并按Ctrl + c
I run a program that have continues output and Ctrl+c after a while
$ ping 127.0.0.1 | python pipetest.py
^C0
我没有输出. 但是,如果我通过普通文件,它就可以工作.
I get no output. But if I go via an ordinary file it works.
$ ping 127.0.0.1 > testfile.txt
一会儿后按Ctrl + c结束
this is ended by Ctrl+c after a short while
$ 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
在程序结束之前如何获取任何输出,在这种情况下ping已结束?
推荐答案
尝试下一个:
import sys
import time
k = 0
try:
buff = ''
while True:
buff += sys.stdin.read(1)
if buff.endswith('\n'):
print buff[:-1]
buff = ''
k = k + 1
except KeyboardInterrupt:
sys.stdout.flush()
pass
print k
这篇关于您如何从没有结尾的管道中读取python中的stdin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文