gpt4 book ai didi

python - 如何将日志记录添加到带有时间戳的文件到 Raspberry Pi 的 Python TCP 服务器

转载 作者:太空狗 更新时间:2023-10-29 20:33:20 26 4
gpt4 key购买 nike

我的项目有点卡住了,我迫切需要帮助。我需要一个简单的 TCP 服务器 python 代码,它具有日志记录和时间戳等功能,我可以将其用于我的 Raspberry Pi。它用于我的毕业设计。

我看过一些示例,但由于我在编写自己的脚本/代码方面没有太多经验,所以我不太确定如何去做。如果有人可以通过解释和一些示例(如果可能的话)指导我朝着正确的方向前进,我将不胜感激。

我正在使用 HERCULES SETUP UTILITY ,它充当我的 TCP 客户端,而我的 visual studio python 代码充当服务器。我的服务器现在可以接收客户端发送的数据,我似乎无法添加可以将发送的数据保存到文本文件中的日志文件。有人可以给我一些例子或引用吗?你的帮助意义重大。到目前为止,这是我的代码:

from socket import *
import thread

BUFF = 1024 # buffer size
HOST = '172.16.166.206'# IP address of host
PORT = 1234 # Port number for client & server to recieve data
def response(key):
return 'Sent by client'

def handler(clientsock,addr):
while 1:
data = clientsock.recv(BUFF) # receive data(buffer).
print 'data:' + repr(data) #Server to recieve data sent by client.
if not data: break #If connection is closed by client, server will break and stop recieving data.
print 'sent:' + repr(response('')) # respond by saying "Sent By Client".



if __name__=='__main__':
ADDR = (HOST, PORT) #Define Addr
serversock = socket(AF_INET, SOCK_STREAM)
serversock.bind(ADDR) #Binds the ServerSocket to a specific address (IP address and port number)
serversock.listen(0)
while 1:
print 'waiting for connection...'
clientsock, addr = serversock.accept()
print '...connected from:', addr #show its connected to which addr
thread.start_new_thread(handler, (clientsock, addr ))

最佳答案

要将日志添加到带有时间戳的文件中,您可以使用 logging 模块:

import logging

logging.basicConfig(level=logging.INFO,
filename='myserver.log', # log to this file
format='%(asctime)s %(message)s') # include timestamp
logging.info("some message")

如果你运行代码;您应该在 myserver.log 中看到(+/- 您的时区和当前时间):

2013-12-24 09:20:17,739 some message

这是一个完整的 TCP 服务器示例,它在每个从客户端接收到的行前加上 "Sent by Client: " 短语并将其发回:

#!/usr/bin/env python
import logging
import sys
from SocketServer import ThreadingTCPServer, StreamRequestHandler

info = logging.getLogger(__name__).info

class EchoLineHandler(StreamRequestHandler):
def handle(self):
info("handling request from %s", self.client_address)
# prepend each line (b'\n') and send it back
for line in self.rfile:
self.wfile.write(b"Sent by Client: ") # assume ascii-based encoding
self.wfile.write(line)
info("done %s", self.client_address)

def test(ServerClass=ThreadingTCPServer, HandlerClass=EchoLineHandler):
# configure logging
logging.basicConfig(level=logging.INFO,
filename='server.log', # log to this file
format='%(asctime)s %(message)s') # include timestamp

# parse command line arguments
host, port = 'localhost', 8826
if len(sys.argv) > 1:
host_, separator, port_ = sys.argv[1].rpartition(":")
port = int(port_)
if separator: # if ":" in sys.argv[1]
host = host_ # accept any host, including empty

# listen for connections
server = ServerClass((host, port), HandlerClass)
info("Serving on %s port %s", *server.server_address)
try:
server.serve_forever()
finally:
info("quit.")

if __name__=="__main__":
test()

如果代码保存在echo_line_server.py中,运行服务器:

$ python -mecho_line_server localhost:8826 & tail -F server.log
2013-12-24 17:09:38,089 Serving on 127.0.0.1 port 8826

运行客户端:

$ echo abc | nc localhost 8826
Sent by Client: abc

关于python - 如何将日志记录添加到带有时间戳的文件到 Raspberry Pi 的 Python TCP 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20695241/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com