Python sys.stdin.read () from tail -f

How did sys.stdin.read () not read the input stream from the -f tail?

#!/usr/bin/env python
import sys
from geoip import geolite2
def iplookup(srcip):
        for ip in srcip.split("\n"):
                try:
                        print(geolite2.lookup(ip))
                except:
                        pass
source = sys.stdin.read()
iplookup(source)

tail -f /var/log/bleh.log | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' | python mygeoip.py

+4
source share
4 answers

You can use sys.stdiniterator rather than try to read it first.

def iplookup(srcip):
    for ip in srcip:
        ip = ip.strip()
        try:
            print(geolite2.lookup(ip))
        except:
            pass

iplookup(sys.stdin)
+1
source

You can use fileinput:

import sys
from geoip import geolite2
import fileinput

def iplookup(srcip):
        for ip in srcip.split("\n"):
                try:
                        print(geolite2.lookup(ip))
                except:
                        pass

for line in fileinput.input():
    iplookup(line)

On the plus side, your script automatically accepts the file name as parameters.

+2
source

( fileinput) tail -f.

python:

, xreadlines(), readlines() ( " sys.stdin" ), . , "sys.stdin.readline()" "1:".

, :

while True:
    line = sys.stdin.readline()
    iplookup(line)
+2
source

read () is read before reaching EOF. The EOF char is added when the close () function is executed, or you can add it explicitly.

There is no EOF in your file. Modify your program to read fixed-size blocks or iterate over leadline ().

0
source

Source: https://habr.com/ru/post/1589262/


All Articles