将输入从终端输入到Python脚本

时间:2017-05-11 10:05:32

标签: python

我的服务器上有一个日志文件,我正在使用CLI程序将内容提取到终端。我需要做一些过滤和json操作,我更喜欢在python而不是在一些bash脚本中这样做。现在我的问题是有没有办法将流传输到python?

类似这样的事情

cliProgram fetchLogs | python script.py 

在Python中,我想逐行解析内容,因此python文件应该有一种逐行读取数据的方法,如果数据不可用(可能是因为网络延迟),它应该等待更多的数据并在流关闭时退出。

1 个答案:

答案 0 :(得分:1)

您只需要迭代sys.stdin

bruno@bigb:~/Work/playground$ cat pipein.py
import sys

def main():
    for line in sys.stdin:
        print "line '%s'" % line.rstrip("\n")

if __name__ == "__main__":
    main()

bruno@bigb:~/Work/playground$ cat wotdata.txt 
E = 0
m = 1
J = 3
K = 2
p = {0: 0.696969696969697, 1: 0.30303030303030304}
UDC = {(0, 1): 9.0, (1, 2): 10.0, (0, 0): 5.0, (1, 1): 6.0, (1, 0): 9.0, (0, 2): 6.0}
UDU = {(0, 1): 5.0, (1, 2): 4.0, (0, 0): 2.0, (1, 1): 4.0, (1, 0): 1.0, (0, 2): 3.0}
UAC = {(0, 1): 1.0, (1, 2): 0.0, (0, 0): 2.0, (1, 1): 3.0, (1, 0): 4.0, (0, 2): 0.0}
UAU = {(0, 1): 9.0, (1, 2): 10.0, (0, 0): 5.0, (1, 1): 6.0, (1, 0): 10.0, (0, 2): 6.0}

bruno@bigb:~/Work/playground$ cat wotdata.txt | python pipein.py
line 'E = 0'
line 'm = 1'
line 'J = 3'
line 'K = 2'
line 'p = {0: 0.696969696969697, 1: 0.30303030303030304}'
line 'UDC = {(0, 1): 9.0, (1, 2): 10.0, (0, 0): 5.0, (1, 1): 6.0, (1, 0): 9.0, (0, 2): 6.0}'
line 'UDU = {(0, 1): 5.0, (1, 2): 4.0, (0, 0): 2.0, (1, 1): 4.0, (1, 0): 1.0, (0, 2): 3.0}'
line 'UAC = {(0, 1): 1.0, (1, 2): 0.0, (0, 0): 2.0, (1, 1): 3.0, (1, 0): 4.0, (0, 2): 0.0}'
line 'UAU = {(0, 1): 9.0, (1, 2): 10.0, (0, 0): 5.0, (1, 1): 6.0, (1, 0): 10.0, (0, 2): 6.0}'