[英]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.