你怎么从没有结束的管道读取python中的stdin

Jan*_*nne 25 python stdin pipe

当管道来自"打开"(不知道正确的名称)文件时,我有问题从python中的标准输入或管道读取.

我有例如 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
Run Code Online (Sandbox Code Playgroud)

我运行了一段时间后继续输出和Ctrl + c的程序

$ ping 127.0.0.1 | python pipetest.py
^C0
Run Code Online (Sandbox Code Playgroud)

我没有输出.但如果我通过一个普通的文件,它的工作原理.

$ ping 127.0.0.1 > testfile.txt
Run Code Online (Sandbox Code Playgroud)

一段时间后,这将以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
Run Code Online (Sandbox Code Playgroud)

如何在程序结束前获取任何输出,在这种情况下ping已经结束?

Rom*_*huk 27

尝试下一个:

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
Run Code Online (Sandbox Code Playgroud)

  • 我不是建议你删除你的答案,只是最后一行错了.我删除了"完全错误"的评论,因为它错了 - 你的程序是正确的,只是你的结束语是错的.我不是downvoter(我不会,因为我不知道你的答案是否有效). (2认同)

woo*_*oot 8

为了使其工作而不等待stdin流结束,您可以在readline上进行操作.我认为这是最简单的解决方案.

import sys
k = 0
try:
   for line in iter(sys.stdin.readline, b''):
      k = k + 1
      print line
except KeyboardInterrupt:
   sys.stdout.flush()
   pass
print k
Run Code Online (Sandbox Code Playgroud)

  • 以这种方式使用 `iter` 很聪明 (3认同)

cod*_*ape 7

k = 0
try:
    while True:
        print sys.stdin.readline()
        k += 1
except KeyboardInterrupt:
    sys.stdout.flush()
    pass
print k
Run Code Online (Sandbox Code Playgroud)


小智 6

这就是我最终这样做的方式。我不太喜欢其他任何解决方案,它们看起来不太Pythonic。

这将为任何打开的文件输入创建一个容器,以迭代所有行。这还将负责在上下文管理器末尾关闭文件。

我觉得这可能就是该for line in sys.stdin:块默认的运行方式。

class FileInput(object):                                                        
    def __init__(self, file):                                                   
        self.file = file                                                       

    def __enter__(self):                                                        
        return self                                                             

    def __exit__(self, *args, **kwargs):                                        
        self.file.close()                                                       

    def __iter__(self):                                                         
        return self                                                             

    def next(self):                                                             
        line = self.file.readline()                                             

        if line == None or line == "":                                          
            raise StopIteration                                                 

        return line  

with FileInput(sys.stdin) as f:
    for line in f:
        print f

with FileInput(open('tmpfile') as f:
    for line in f:
        print f
Run Code Online (Sandbox Code Playgroud)

从命令行,以下两项都应该有效:

tail -f /var/log/debug.log | python fileinput.py
cat /var/log/debug.log | python fileinput.py
Run Code Online (Sandbox Code Playgroud)

  • @Kellen Fox——你可能已经实现了你的愿望!http://stackoverflow.com/a/1454400/188963 https://docs.python.org/3/library/fileinput.html (3认同)