I am creating a log watcher to emulate the tail-f
functionality in Linux. So, basically here's what I wanna do
But here's whats happening
Here is my code server.py
import socket
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1243))
s.listen(5)
class Tail():
def __init__(self,file_name,callback=sys.stdout.write):
self.file_name = file_name
self.callback = callback
def follow(self,n):
try:
with open(self.file_name) as f:
self._file = f
self.showLastLine(n)
self._file.seek(0,2)
while True:
line = self._file.readline()
if line:
self.callback(line)
except Exception as e:
print('Failed to open the file. See if the file does not exist or if there is a problem with permissions')
print(e)
def showLastLine(self, n):
last_lines = self._file.readlines()[-10:]
for line in last_lines:
self.callback(line)
py_tail = Tail('log.log')
while True:
clientsocket, address = s.accept()
clientsocket.send(bytes(py_tail.follow(10),"utf-8"))
client.py
import socket
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 1243))
while True:
msg = s.recv(16)
msg.decode("utf-8")
print(msg)
for now I have just created a dummy log.log
file which looks something like this
1
2
3
4
5
so when I edit the log file and type
6
7
8
and save it the changes are reflected in the output of my server.py file, but I want the output to be displayed on my client.py
file, which is not happening.
I am just exploring socket programming, and since I am new to this, this might be silly query that I have but I really need help.
I have changed the code accordingly and this is how I could fix it
server.py
import socket
import time
import sys
import os
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1243))
s.listen(5)
def follow(thefile):
'''generator function that yields new lines in a file
'''
# seek the end of the file
thefile.seek(0, os.SEEK_END)
# start infinite loop
while True:
# read last line of file
line = thefile.readline()
# sleep if file hasn't been updated
if not line:
time.sleep(0.1)
continue
yield line
logfile = open("log.log","r")
loglines = follow(logfile)
while True:
clientsocket, address = s.accept()
for line in loglines:
clientsocket.send(bytes(line,"utf-8"))
client.py
import socket
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((socket.gethostname(), 1243))
while True:
lines = s.recv(16)
lines=lines.decode("utf-8")
print(lines)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.