这是我用来接收系统日志并将其附加到文本文件的脚本:
# Receives packets on udp port 514 and
# writes to syslog.txt
from socket import *
# Set the socket parameters
host = "myhost"
port = 514
buf = 1024
addr = (host,port)
# Create socket and bind to address
UDPSock = socket(AF_INET,SOCK_DGRAM)
UDPSock.bind(addr)
# Receive messages
while 1:
data,addr = UDPSock.recvfrom(buf)
if not data:
print "Client has exited!"
break
else:
print "\nReceived message '", data,"'"
# This will create a new file or overwrite an existing file.
with open("C:\syslog.txt", "a") as myfile:
myfile.write(str(data))
# Close socket
UDPSock.close()
脚本工作正常,文本附加到文件中。我看到了,而且读得很好。但是,在我关闭 python 的那一刻,该 txt 文件数据被翻译成乱码。任何想法为什么?在将套接字数据附加到文件之前我应该做其他事情吗?
谢谢。