[英]How to print data on client side using Python
我正在创建一个日志观察器来模拟 Linux 中的tail-f
功能。 所以,基本上这就是我想做的
但这是发生了什么
这是我的代码 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"))
客户端.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)
现在我刚刚创建了一个虚拟的log.log
文件,它看起来像这样
1
2
3
4
5
所以当我编辑日志文件并输入
6
7
8
并保存更改会反映在我的 server.py 文件的输出中,但我希望输出显示在我的client.py
文件中,但这并没有发生。
我只是在探索套接字编程,因为我是新手,这可能是我的愚蠢查询,但我真的需要帮助。
我已经相应地更改了代码,这就是我可以修复它的方法
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.