簡體   English   中英

如何使用 Python 在客戶端打印數據

[英]How to print data on client side using Python

我正在創建一個日志觀察器來模擬 Linux 中的tail-f功能。 所以,基本上這就是我想做的

  1. 編寫可以檢測日志文件中發生的更改的服務器代碼。
  2. 如果在日志文件中檢測到更改,服務器應將數據發送到客戶端,客戶端應打印數據。

但這是發生了什么

  1. 服務器上的代碼能夠檢測日志文件中發生的更改。
  2. 但是更改僅在服務器端打印,即使我將服務器日志發送到客戶端
  3. 客戶端沒有打印任何內容。

這是我的代碼 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM